Unity3D - When is DontDestroyOnLoad destroyed?

Do I need to destroy it before I disable the app? or after they take away their GB?

How does DontDestroyOnLoad work? has link count?

+3


source to share


2 answers


Objects created in the scene (by default) are destroyed when a new scene (level) is loaded. By using DontDestroyOnLoad, you are saying that you DO NOT follow this behavior to keep the object constant across levels. You can always remove it by calling the Destroy () function.

From the documentation :



There is no way to automatically destroy the target of an object when loading a new scene. When loading a new level, all objects in the scene are destroyed, then the objects of the new level are loaded. To save the object while the level is loading, type DontDestroyOnLoad on it. If the object is a component or game object, then its entire transformation hierarchy will not be destroyed either.

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void Awake() {
        DontDestroyOnLoad(transform.gameObject);
    }
}

      

+3


source


When changing scenes, all non-static objects in that scene are destroyed. When an object is marked as DontDestroyOnLoad

, it will not be destroyed when the scene changes.

If you later want to destroy this object , you can call

Destroy(objName);

      

which is sometimes useful if you go back to the scene that originally created the object. If you could not destroy one or could not verify that it already exists before creation, you will receive 2 objects of the same type and both will be indestructible.



If your application exits, you don't have to worry about destroying anything yourself, it will be done for you.


Another way to make the object stay alive throughout the entire execution of the program is to make it static.

public static class DataContainer
{
}

      

+3


source







All Articles