63 lines
1.8 KiB
C#
63 lines
1.8 KiB
C#
using UnityEngine;
|
|
|
|
namespace A2W
|
|
{
|
|
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
|
|
{
|
|
private static T _instance;
|
|
private static object _lock = new object();
|
|
public static T instance
|
|
{
|
|
get
|
|
{
|
|
//if (applicationIsQuitting)
|
|
//{
|
|
// return null;
|
|
//}
|
|
|
|
if (_instance == null)
|
|
{
|
|
lock (_lock)
|
|
{
|
|
if (_instance == null)
|
|
{
|
|
var objs = FindObjectsByType<T>(FindObjectsSortMode.None);
|
|
if (objs.Length > 0)
|
|
{
|
|
_instance = objs[0];
|
|
if (objs.Length > 1)
|
|
{
|
|
for (var i = 1; i < objs.Length; i++)
|
|
{
|
|
Destroy(objs[i].gameObject);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (_instance == null)
|
|
{
|
|
var singleton = new GameObject();
|
|
_instance = singleton.AddComponent<T>();
|
|
singleton.name = "(singleton)" + typeof(T).ToString();
|
|
|
|
DontDestroyOnLoad(singleton);
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
return _instance;
|
|
}
|
|
}
|
|
|
|
//private static bool applicationIsQuitting = false;
|
|
|
|
//public void OnDestroy()
|
|
//{
|
|
// applicationIsQuitting = true;
|
|
//}
|
|
}
|
|
}
|
|
|