API: Object.DontDestroyOnLoad

Description

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);
    }
}

Examples of usage scenarios:

In the Start method of a script in scenario 1, DontDestroyOnLoad(A)

Then switch to scene 2, of course the A object is retained

If you go back to scene 1 from scene 2 again, then execute DontDestroyOnLoad(A) again, but your A object has not been cast before, so the wireless loop will continue.

Solutions such as:

1. A cache scene can be established, and all objects that need to be retained are placed under an empty object, which ensures that the retention cycle and retention repetition problems are guaranteed.

2. The same object judgment method can be used.

Guess you like

Origin blog.csdn.net/qq_40513792/article/details/114819977
API