MonoSingleton(Unity Singleton)
[파일]
using UnityEngine;
namespace Core
{
public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
private static bool m_bApplicationQuit = false;
private static object InstanceLocker = new object();
private static T m_Instance = null;
public static T Instance
{
get
{
if (true == m_bApplicationQuit)
return null;
lock (InstanceLocker)
{
if (null == m_Instance)
{
T instance = FindAnyObjectByType<T>();
if (null == instance)
{
instance = new GameObject(typeof(T).ToString()).AddComponent<T>();
if (null == instance)
{
Debug.LogError("Problem during the creation of " + typeof(T).ToString());
}
}
if (null != instance)
{
Initialize(instance);
}
}
return m_Instance;
}
}
}
public static void SetInstance(T _cInstance)
{
m_Instance = _cInstance;
}
public static bool Exists
{
get
{
if (null == m_Instance || null == m_Instance.gameObject)
{
return false;
}
return true;
}
}
protected virtual void Awake()
{
Initialize(this as T);
}
private static void Initialize(T instance)
{
if (null == m_Instance)
{
#if UNITY_EDITOR || DEVELOPMENT_BUILD
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
#endif
m_Instance = instance;
m_Instance.OnInitialize();
#if UNITY_EDITOR || DEVELOPMENT_BUILD
stopwatch.Stop();
if (1.0 < stopwatch.Elapsed.TotalSeconds)
{
Debug.LogWarning($"[MonoSingleton] {typeof(T).Name} init: {stopwatch.Elapsed.TotalSeconds:F2}s");
}
#endif
}
else if (m_Instance != instance)
{
if (true == Application.isPlaying)
{
Destroy(instance.gameObject);
}
else
{
DestroyImmediate(instance.gameObject);
}
}
}
private static void Destroyed(T instance)
{
if (null != m_Instance && m_Instance == instance)
{
m_Instance.OnFinalize();
m_Instance = null;
}
}
public void CreateSingleton() { }
public virtual void OnInitialize() { }
public virtual void OnFinalize() { }
public virtual void DoDestroy() { OnDestroy(); }
void OnDestroy()
{
Destroyed(this as T);
}
private void OnApplicationQuit()
{
m_bApplicationQuit = true;
Destroyed(this as T);
}
static Transform GetParent(Transform _trTarget)
{
if (null != _trTarget.parent)
return GetParent(_trTarget.parent);
return _trTarget;
}
public void SetDontDestroy()
{
if (null == m_Instance)
return;
Transform trRoot = GetParent(this.transform);
if (true == Application.isPlaying)
{
DontDestroyOnLoad(trRoot);
}
}
}
}
'Unity3D > Script' 카테고리의 다른 글
| A simple cross fade shader for Unity (0) | 2014.04.22 |
|---|---|
| 어플을 내렸을때, 어플을 종료할때의 처리 (3) | 2014.04.04 |
| Platform Dependent Compilation (0) | 2014.03.11 |
| Generic Based Singleton for MonoBehaviours完全版(?) (0) | 2014.03.05 |
| Singleton (0) | 2014.03.05 |
