0
\$\begingroup\$

I have the following in a script attached to a game object in a unity scene. When I run this scene and press 'E', I get the following logs. (The game object is destroyed too)

In destroy
After destroy

void Update () {
    if(Input.GetKey(KeyCode.E)){
        Debug.Log ("In destroy");
        Destroy (gameObject);
        Debug.Log ("After destroy");
    }
}

My question is that if the game object is destroyed, then why does the execution continue to the code which logs "After destroy"?

\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

It's just finishing the current frame as the task in the same frame on Update().

If you test like below you will not see anything form next frame. LateUpdate() is executed in next the frame after Update() execution.

void Update()
{
    if (Input.GetKeyDown(KeyCode.E))
    {
        Debug.Log("In destroy");
        Destroy(this.gameObject);
    }
}
void LateUpdate()
{
    if (Input.GetKeyDown(KeyCode.E))
    {
        Debug.Log("After destroy");
    }
}
\$\endgroup\$
1
\$\begingroup\$

I found the reason for this. As per the Unity documentation (at this link), the actual object destruction is always delayed until after the current Update loop. Therefore, the current update method is executed and the logs are printed.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .