I am taking the Unity Junior Programmer Tutorial Series and am on Unit 5.4. The instructor tells us to put in the following code:
Destroy (gameObject);
if ( ! gameObject.CompareTag(“Bad”) {
gameManager.GameOver();
}
My question is that if the game object has been destroyed, how can you reference its tag or anything else about it? When I test whether I put the Destroy game object before or after the if statement, it doesn’t make any difference. The code still works the same way. I am using Unity 2018.4…31f1
I’m not 100% sure but my assumption would be that, like a lot of processes in Unity, the ‘Destroy’ method only gets committed at the end of that frame/containing method.
It would be worth trying to call the game object again the next frame from a different source (like a different game object)
You won’t run into any errors destroying a game object from itself because once the game object is destroyed it’s ‘Update’ method stops being called
Hope that was helpful
I think Destroy is more of a Unity term, meaning it gets destroyed from your scene. It can still exist in memory until GC runs and until that happens, it’s still an object that exists…just not in your scene.
The code is within an OnTrigger event. Update is not used at all in the game. I see that all of the answers so far have been guesses. I like the idea that the object is destroyed in the scene but is still present in memory and continues within the method I am in until that method is exited. That makes sense; otherwise, the script would simply abort right after the Destroy has been executed since it is a component of the game object being destroyed. Since the script is still executing, the references to the game object remain so that you can still get its position and other attributes. Exactly when the actual components of the game object are eventually removed, I think the only person that can answer that is a person who knows exactly how the game engine works. I believe that it makes good programming sense to put the Destroy(gameObject) after I do what needs to be done with its references. This would appear to be more logical and easy to follow.
private void OnTriggerEnter()
{
if (!gameObject.CompareTag("Bad"))
{
gameManager.GameOver();
}
Destroy(gameObject);
}