21

Unity中DontDestroyOnLoad在切换场景时的坑点-腾讯游戏学院

 5 years ago
source link: http://gad.qq.com/article/detail/288282
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
在unity中我们经常要用到DontDestroyOnLoad来使一个gameobject在切换场景的时候不被销毁而保留下来,但是有时会遇到这样的情况,在Loading场景建立一个空物体,我给它起名叫test,上面挂一个脚本,如图
5be6fcfc60aeb.png
脚本里的代码是这样的
void Start () 
{
    DontDestroyOnLoad(this);
}
这段代码只有一个作用,那就是使test这个物体在切换场景的时候不被销毁而保留下来

一开始我从Loading场景切换到Main场景,结果是这样的
5be6f7812b2ab.png
ok,现在看起来很正常,test被保留了下来

现在我在Main场景加一个按钮,这个按钮的作用是切换回Loading场景,然后我按下那个按钮,现在场景被切换回了Loading场景,如图
5be6f895e09aa.png
现在,你发现了什么,test物体变成了两个!
这绝对不是我们想要的,那么如何解决这个问题呢?
可以在想要切换场景保留的物体上加一个单例类,当然啦,这个类最好是有实际的作用,这个单例类实现如下
private static RequestManager _instance;
public static RequestManager Instance { get { return _instance; } }
private void Awake()
{
	if (_instance != null)
	{
		Destroy(this.gameObject); return;
	}
	else
	{
		_instance = this;
	}
}
这里的RequestManager就是你要加的单例类的类名,你可以更换成你的单例类的类名,然后把他挂载到test物体上,然后我们重新测试一下,由Loading场景切换到Main场景,再点击按钮切换回Loading场景,现在的结果,如图
5be6fc081afe7.png
这次只有一个test物体,这样就不会出现由Main场景切换回Loading场景时,产生两个物体test了。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK