使用DontDestroyOnLoad的坑
今天使用DontDestroyOnLoad();不销毁对象,当我的几个场景来回跳转的时候出现了问题,会重复生成这个不销毁的对象,可是我要的效果是无论怎么跳转就只存在一个这样的对象。
这是我写的代码
// ========================================================
// 描述:
// 作者:MeKey
// 创建时间:2019-05-14 17:49:30
// 版 本:1.0
// ========================================================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Dotdestroy : MonoBehaviour {
private void Awake()
{
DontDestroyOnLoad(gameObject);
}
}
解决DontDestroyOnLoad的坑
更改脚本,挂到不销毁对象的物体上。而且这个脚本是个单利脚本。
/// ========================================================
// 描述:
// 作者:MeKey
// 创建时间:2019-05-14 17:49:30
// 版 本:1.0
// ========================================================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Dotdestroy : MonoBehaviour
{
private static Dotdestroy instance;
public static Dotdestroy Instance
{
get { return instance; }
}
private void Awake()
{
if (instance != null)
{
Destroy(gameObject);
return;
}
instance = this;
DontDestroyOnLoad(gameObject);
}
}
这是我场景来回跳转几次之后的截图,只有唯一的一个对象。
微信公众号会定期推送一些资源