2种方式解决DontDestroyOnLoad物体重复保留

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/itsxwz/article/details/84302331

1.使用该api的物体不销毁
2.使另一个物体不销毁

Example1:
public class DontDestroy : MonoBehaviour {
    private void Start() {
        DontDestroyOnLoad(this.gameObject);
    }
}
Example2:
    private void Start() {
        GameObject go = (GameObject)Instantiate(Resources.Load("KeepObject"));
        DontDestroyOnLoad(go);
   }

上述两种方式的不销毁,在返回挂载有该脚本的场景时会被重新执行对应函数逻辑

解决方案:
1.用一个static开关控制逻辑只执行一次(只保留一份)
2.“不销毁物体”除了第一个以外,其他都删除(重复保留再删除)

Example1:
    private static bool isCloning = false;
    private void Start() {
        if(!isCloing){
        	GameObject go = (GameObject)Instantiate(Resources.Load("KeepObject"));
            DontDestroyOnLoad(go);
            isCloing = true;
        }
   }
Example2:
    private static DontDestroy instance;
    private DontDestroy() { }
    public static DontDestroy Instance {
        get {
            return instance;
        }
    }

	void Start () {
        if (instance != null) {
            Destroy(this.gameObject);
            return;
        } else {
            instance = this;
        }
    }

猜你喜欢

转载自blog.csdn.net/itsxwz/article/details/84302331