Ondestroy in Unity

Asked

Viewed 134 times

-2

Hello, could someone explain to me how Ondestroy() works in Unity? What is your specific action. The documentation is very confusing.

1 answer

0


Just as its name says, Ondestroy is a function that is called when the object is destroyed, it can happen when:

  • A scene change occurs (When we work with more than one scene in Unity, by switching between them, the Ondestroy method is called, and everything inside it will be executed. This is because when a new scene is called, the current scene and all the objects in it are destroyed).

  • When the Destroy() function is called (The Destroy() function forces the object to destroy itself, and when this happens, the Ondestroy function is executed, and in it you can put what you want to happen when the object is destroyed, for example an animation).

In short

The Ondestroy function is invoked when the object is destroyed, and you can use it to do something when it happens.

Example of the Ondestroy() method applied to an object:

void OnDestroy()
{
   Debug.Log("Estou sendo destruido!!");
   // Rodar animação ou fazer algo
}

References: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnDestroy.html

  • Thank you so much, you helped so much!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.