123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
-
- using System;
- using UnityEngine;
- public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
- {
- protected static T _insatnce;
- protected static object _lock = new object();
- public static T Instance
- {
- get
- {
- lock (_lock)
- {
- if (_insatnce == null)
- {
- var instances = FindObjectsOfType<T>();
- if (instances.Length > 1)
- {
- throw new Exception(string.Format("场景中存在多个类型为:{0}的脚本", typeof(T).ToString()));
- }
- else if (instances.Length == 0)
- {
- var go = new GameObject(typeof(T).ToString() + "(MonoSingleton)");
- _insatnce = go.AddComponent<T>();
- //DontDestroyOnLoad(go);
- }
- else
- {
- _insatnce = instances[0];
- }
- //if (instances.Length > 1)
- //{
- // _insatnce = instances[0];
- //}
- //else
- //{
- // var go = new GameObject(typeof(T).ToString() + "(MonoSingleton)");
- // _insatnce = go.AddComponent<T>();
- // //DontDestroyOnLoad(go);
- //}
- }
- return _insatnce;
- }
- }
- }
- protected virtual void OnApplicationQuit()
- {
- _insatnce = null;
- }
- protected virtual void OnDestory()
- {
- _insatnce = null;
- }
- }
|