How to properly check if unityevent is null?
I'm trying to use unity event and i have a if condition
if (uEvent != null)
{
print("uEvent wasn't null");
// do something
}
else
{
print("uEvent was null");
// do something else
}
but when i run it unity thinks that uEvent ISN'T null but it doesn't throw an error. This has never happend to me in my life before and I have no clue how to fix this
Answer by brekelmansjelle8 · Mar 11, 2019 at 10:30 AM
Kind of a late reply, but thought I'd leave it just in case someone could still use it.
I am assuming you have a UnityEvent reference somewhere in your script that you fill within the editor, and that you want to check if an event is actually added. If this is the case, then use the following solution:
The UnityEvent object ITSELF is not null, it's just that the listeners have not been added. The solution is to loop through the pestistent events and check if one of the targets ISN'T null, meaning you can execute this target's method. Some example code:
bool hasPersistentTarget = false;
for (int i = 0; i < clickEvent.GetPersistentEventCount(); i++)
{
if (clickEvent.GetPersistentTarget(i) != null)
{
hasPersistentTarget = true;
}
}
NOTE: This does NOT check for non persistent events and only checks if a TARGET is added, not if one of it's FUNCTIONs is selected!
This helped a ton! Thanks for the explanation.
Personally, I added a break;
after hasPersistentTarget = true;
so it doesn't loop any unnecessary times. This probably only gives you a nanosecond faster performance but might as well add it.
:D
Your answer
Follow this Question
Related Questions
Notifying about character/item selection 1 Answer
Unity Event not getting invoked. 0 Answers