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

使用场景举例:

在场景1中某一个脚本的Start方法中,DontDestroyOnLoad(A)

接着切换到场景2中,理所当然A对象被保留了下来

如果在从2场景再次回到1场景,那么又执行了一遍DontDestroyOnLoad(A)然而之前你的A对象却没有被施放,这样就会无线循环下去了。

解决方法如:

1.可以建立缓存场景,将需要保留的所有对象放在一个空的对象下,这样保证了保留一直循环和保留重复的问题,

2.可以使用相同对象判断方法。

猜你喜欢

转载自blog.csdn.net/qq_40513792/article/details/114819977
今日推荐