Consider the simple scenario of:
Destroy(gameObject, 5f);
Destroy(gameObject);
At least in my version of Unity (2019.4.4f1) this doesn’t seem to throw any errors, but the documentation doesn’t specify if it’s safe to do. The use case I have in my game is destroying a mouse cursor effect when the user clicks again, or after a certain amount of time, like this:
if (_lastCursor != null) {
Destroy(_lastCursor);
}
_lastCursor = Instantiate<GameObject>(cursorClickPrefab);
Destroy(_lastCursor, .5f);
I guess in theory this could also be solved by writing a coroutine which checks after the given amount of time if the object wasn’t destroyed and uses Destroy
without a timeout instead, but if this is safe it would be unnecessary.
Any thoughts?
if you try to destroy an object twice, one will come first and succeed, and the other will raise a NullRefrenceExeption.
even though unity scripts are separate, when compiled, 2 lines of code cannot be executed at once. this is why when you have an infinite loop in an IEnumerator() even though you need to call it with something called startCoroutine() (which sounds like if it crashed only the coroutine would be broken) would crash your whole game because of the infinite loop. so i would change
Destroy(_lastCursor, .5f);
to
if(_lastCursor) Destroy(_lastCursor, .5f);
.
if you try to destroy an object twice, one will come first and succeed, and the other will raise a NullRefrenceExeptio
I’m confused why you’re saying this, because even if I literally call Destroy(x); Destroy(x)
, that is destroy it twice in a row, I don’t get a NullReferenceException
, and I also don’t get it on the delayed destroy.
Is this something that depends on Unity version?