Reputation: 41
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?
Upvotes: 3
Views: 6272
Reputation: 7824
When you change scenes all non-static objects in that scene are destroyed. When an object is marked as DontDestroyOnLoad
it won't be destroyed when changing scenes.
If later you wish you destroy that object you can call
Destroy(objName);
which is sometimes useful if you return to the scene that originally created the object. If you fail to Destroy one or fail to check it already exists before creating you will end up with 2 objects of the same type and both being indestructible.
If your application exits you won't have to worry about destroying anything yourself, it will be done for you.
Another way to make an object stay alive through the whole execution of a program is to make it static.
public static class DataContainer
{
}
Upvotes: 3
Reputation: 6123
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);
}
}
Upvotes: 3