美文网首页unity
Unity3D之DontDestroyOnLoad的坑

Unity3D之DontDestroyOnLoad的坑

作者: 清歌AND浊酒 | 来源:发表于2018-03-22 10:58 被阅读7次

最近在做一个虚拟仿真的项目,用到了DontDestroyOnLoad总结下这个坑。
DontDestroyOnLoad可以让某些对象在切换场景的时候不是施放,如果没有用好就会出现问题。
举个例子:
在场1中你要实现DontDestroyOnLoad(A),然后跳转到2场景中,再从场景2中跳转到场景1中,那么DontDestroyOnLoad(A)就会又执行一遍,这样就会形成一个死循环。
借鉴了雨凇momo的一篇文章具体代码如下:

using UnityEngine;
using System.Collections;
 
public class Global :MonoBehaviour
{
    public static Global instance;
 
    static Global()
    {
        GameObject go = new GameObject("Globa");
        DontDestroyOnLoad(go);
        instance = go.AddComponent<Global>();
    }
 
    public void DoSomeThings()
    {
        Debug.Log("DoSomeThings");
    }
 
    void Start () 
    {
        Debug.Log("Start");
    }
 
}

利用static 初始化方法,当代码在调用Global类的时候,首先程序会进入static Global方法中,这个方法永远只会走一遍,所以我在这里创建一个GameObjcet,然后把Global这条脚本绑定上去,我在DontDestroyOnLoad这个对象。

相关文章

网友评论

    本文标题:Unity3D之DontDestroyOnLoad的坑

    本文链接:https://www.haomeiwen.com/subject/knooqftx.html