最近在写项目时,在结束程序或切换场景时会报 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 _applicationIsQuitting = false;

        protected MonoSingleton() {}

        public static T Instance {

            get
            {
                if(_instance == null && !_applicationIsQuitting) {

                    _instance = Create();
                }
                return _instance;
            }
        }

        private static T Create() {

            var go = new GameObject(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 OnDestory() {

            _applicationIsQuitting = true;
        }
    }

What doesn’t kill you makes you stronger.