版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/CJB_King/article/details/102784813
问题描述
Unity游戏开发中,有时在结束程序或切换场景时会报 Some objects were not cleaned up when closing the scene的错误。意思是,在退出场景时,部分obj没有被清理,引发了内存泄露
解决防范
代码语言:javascript复制public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
private static bool _applicationIsQuit = false;
protected MonoSingleton() { }
public static T instance{
get
{
if(_instance==null&&!_applicationIsQuit)
{
_instance = Create();
}
return _instance;
}
}
private static T Create()
{
GameObject go = new GameObject("[MonoSingleton]" typeof(T).Name, typeof(T));
DontDestroyOnLoad(go);
return go.GetComponent<T>();
}
protected virtual void OnApplicationQuit()
{
if (_instance == null) return;
Destroy(_instance.gameObject);
_instance = null;
}
protected virtual void OnDestroy()
{
_applicationIsQuit = true;
}
}