DontDestroyOnLoad重复创建问题解决办法

方案一:

使用静态构造,把所有需要保留的对象挂载在名为“ Global ”的空对象下,并设置 tag 为“ Global ”,再把一下代码脚本挂载在 Global 上,只有两句代码:



public class Global:MonoBehaviour

{

    public static Globalinstance;

    static Global()

    {

        GameObjectgo=newGameObject("Globa");

        DontDestroyOnLoad(go);

        instance=go.AddComponent();

    }

}

方案二:判断是否存在这个名字的游戏对象,若有则销毁它



private void Awake()

    {

        if (GameObject.FindGameObjectsWithTag("Global").Length>1)

            Destroy(this.gameObject);

        else

            DontDestroyOnLoad(this.gameObject);

    }

你可能感兴趣的:(DontDestroyOnLoad重复创建问题解决办法)