popcorn/Scripts/Utilities/SingletonMonoBehaviour.cs

48 lines
1.1 KiB
C#
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine;
 
public abstract class SingletonMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour {
private static T instance;
public static T Instance {
get{
FindInstance();
if(instance == null){
Debug.LogError(typeof(T) + " is nothing.");
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#endif
}
return instance;
}
}
public virtual void OnDestroy(){
if(instance == this) instance = null;
}
protected bool CheckInstance(){
if(this != Instance){
#if UNITY_EDITOR
Debug.LogError(typeof(T) + " is already exists.");
UnityEditor.EditorApplication.isPlaying = false;
#endif
Destroy(this);
return true;
}else{
return false;
}
}
private static void FindInstance(){
if(instance == null){
instance = (T)FindObjectOfType(typeof(T));
}
}
public static bool ExistsInstance{
get{
FindInstance();
return instance != null;
}
}
}