hi, i have an enemy script that stores a reference to other another entity or the player in the form of a rigidbody for doom style infighting. that all works beautifully, but once in a while i get a missing reference exception, due to an enemy dying and an enemy losing it’s target. normally, i just prevent it from happening in the first place, but i don’t want the enemies all connecting to eachother to send some kind of message that they’ve died, as each enemy would have to know who’s targeting it before death. that’s why i’ve just been TRYing to CATCH the exception. 
anyway, i’ve tried to use try catch, ive tried the ?? operator, even though unity really doesn’t want you to, and i’ve tried if(target != null). from what i understand, the reason the latter doesn’t work is because the object is destroyed but likely still in memory, so it doesn’t return as null.
try catch method seems to have the least frequent errors, but they’re still there occasionally. is there anything i can do? or is this likely just due to human error somewhere?
here’s my try catch statement.
//if the target is gone, switch targets back to the player and end the alert.
try { currentTarget.gameObject.GetHashCode(); }
catch (MissingReferenceException) {
currentTarget = player.GetComponent<Rigidbody>();
Sleep();
}
Not quite how it works. Unity objects can be a ‘fake null’, ergo situations where the underling C++ object has been destroyed but the C# class is still referenced, or where no actual Unity object asset is being referenced. On top of this, Unity objects have a custom overload for the ==
and !=
operators which as part of a number of other checks, does a check for this fake null.
So if a !=
check is passing, then there is a non-destroyed (alive) Unity object in question here.
Note that you should be getting a different error if there is no reference to a Unity object, or if the Unity object has been destroyed.
THAT SAID, this is absolutely not a correct use of try-catch here. You should not be using exception handling for something like this. Exception handling should be to handle situations that are otherwise unrecoverable, not to simply check if something is null or not. You should just write your code to not throw exceptions like this.
1 Like
To complete what spiney199 said, the ??
operator isn’t overloaded by Unity, you shouldn’t use it on Unity objects (Why Are Null-Coalescing Operators (??, ??=) Evil in Unity? | by No Such Dev | Medium)
Maybe you don’t catch the exception because it’s not a MissingReferenceException
but a NullReferenceException
that is thrown (write catch (Exception)
to catch them all).
But please, don’t use exception handling here.
2 Likes
i turned my brain on and realized that the smart thing to do would be just setting the enemy to inactive and destroying it with a delay, and testing whether the target is active instead of null.
sometimes you get so stuck on doing something one way, it’s hard to see the easy way in front of you lol.