0

Here is my problem:

I have a script (in unity, c#), instantiated in multiple objects, that should send messages to a unique object. E.g.:

public delegate void DeathDelegate(string name, float q)
public event DeathDelegate OnDeathEvent;

But when an instantiated object (with the same script) try to send a message comes the error

NullReferenceException: Object reference not set to an instance of an object

I understood that is not possible to do so with a delegate on multiple instantiated objects but I can grasp how could achieve that in an other way. Any help would be appreciated! Thx!!

b.stico
  • 1
  • 1
  • Just a small side note: The use of the `On*` name for events isn't standard. Events should be `Click`. The method on the object that raises the event is typically called `OnClick`. – Enigmativity Nov 22 '20 at 21:00
  • Looks like you have a many to one relation where any caller object should inform the unique listener. You could try to make the event static so listener is on the class level, no longer the object level. – Everts Nov 22 '20 at 21:09
  • @Everts how can I do that? – b.stico Nov 22 '20 at 21:31
  • @Everts - Static events sound like a bad idea to me. – Enigmativity Nov 22 '20 at 22:04
  • In this case, its not a matter of which object sends the event but any object of the type. So static coupd be kind of the way to go. Possible to do without though if there'd be any reason not to use. – Everts Nov 23 '20 at 07:17
  • Just add static keyword and refer to the event as ClassType.EventName. – Everts Nov 23 '20 at 07:18

1 Answers1

0

You are probably missing an assignment to the delegate;

public delegate void DeathDelegate(string name, float q);
public event DeathDelegate OnDeathEvent;

void Start()
{
     OnDeathEvent += (name, q) => Debug.Log("It works now?"); //Missing line
}

And your invoke should not rely on calling delegate as a method, because as you noticed sometimes, it can reference a null. You need to check if OnDeathEvent is not null.

OnDeathEvent?.Invoke("test", 1f);
// or an equivalent
if(OnDeathEvent != null)
{
    OnDeathEvent("test", 1f);
}

PS: You can send messages to unique objects, you need to fix your errors first

Tomasz Juszczak
  • 1,705
  • 12
  • 23