Unity开发单例模式防止内存泄漏

问题描述

Unity游戏开发中,有时在结束程序或切换场景时会报 Some objects were not cleaned up when closing the
scene的错误。意思是,在退出场景时,部分obj没有被清理,引发了内存泄露

解决防范

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;
    }

}

你可能感兴趣的:(Unity开发单例模式防止内存泄漏)