Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity3D - When is "DontDestroyOnLoad object" destroyed?

Am I have to destroy it before turn off the application? or after quit GB collect them?

How Does DontDestroyOnLoad works? has a ref count stuff?

like image 722
김성환 Avatar asked Mar 16 '26 11:03

김성환


1 Answers

Objects instantiatied in a scene are (by default) destroied when a new scene (level) is loaded. Using DontDestroyOnLoad you are telling to NOT follow this behaviour, so that the object will be persistent among levels. You can always delete it by calling Destroy() function.

From the documentation:

Makes the object target not be destroyed automatically when loading a new scene. When loading a new level all objects in the scene are destroyed, then the objects in the new level are loaded. In order to preserve an object during level loading call DontDestroyOnLoad on it. If the object is a component or game object then its entire transform hierarchy will not be destroyed either.

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void Awake() {
        DontDestroyOnLoad(transform.gameObject);
    }
}
like image 62
Andrea Avatar answered Mar 21 '26 06:03

Andrea



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!