#Invoking Action with no subscribers

1 messages · Page 1 of 1 (latest)

lucid fractal
#

I'm trying to use an OnHit action that I made by doing OnHit.Invoke() but when it has no subscribers, it gives NullReferenceError. I then tried to do the following but I still get NullReferenceError on the conditional.

if(OnHit.GetInvocationList().Length > 0)
    OnHit.Invoke();
latent plank
#

A delegate/event that has no subscribers should be null. You can safely invoke it by doing OnHit?.Invoke()

#

The null ref exception you got should have made that clear

lucid fractal
#

Thanks

latent plank
#

Related note, I recommend use of the event keyword:
public event Action OnHit;

lucid fractal
latent plank
#

Great 👍

lucid fractal
#

Thanks for the help

remote cairn
#

btw, you may have heard that ?. isn't safe to use in Unity

#

this is specifically for unity objects -- anything inheriting from UnityEngine.Object

#

it's "unsafe" because it only checks if the object is actually a null reference

#

unity objects have overloaded the == operator so that obj == null is true when obj is a destroyed unity object

#

?. will not check for this, so obj?.transform will throw an error if obj is destroyed

lucid fractal
#

But that is not relevant in the case of actions, right?