美文网首页Unity必看技术贴
如何使游戏对象切换场景后不释放?DontDestroyOnLoa

如何使游戏对象切换场景后不释放?DontDestroyOnLoa

作者: 半夏半暖半倾城灬 | 来源:发表于2021-09-07 15:42 被阅读0次

有时候我们想要保存一个全局的游戏脚本,比如封装的SDK需要用脚本来做中间件的支持,并且场景切换后仍要留存。

那么游戏对象切换场景如何不释放?答:使用DontDestroyOnLoad(GameObject gameObject)方法。

使用该方法会有一个问题,比如我们在A场景里DontDestroyOnLoad(gameObjectA),则我们切换到B场景时GameObjectA不会被释放掉,然后我们再切换回场景A,会发现出现了两个gameObjectA

解决方案1

创建一个初始化场景,在创建的某个游戏对象的全局脚本中,Start方法里DontDestroyOnLoad(this),

void Start(){

    DontDestroyOnLoad(this)

}

然后进入自己的第一个游戏场景,且不再返回初始化场景,也就不会出现来回切场景DontDestroyOnLoad没有删除的问题

解决方案2

利用静态构造函数只会执行一次的特性来执行DontDestroyOnLoad方法

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

}

}

相关文章

网友评论

    本文标题:如何使游戏对象切换场景后不释放?DontDestroyOnLoa

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