Last active
January 27, 2019 00:02
-
-
Save jasoncg/aaad7393caa3e47c84e881030edc4b0c to your computer and use it in GitHub Desktop.
MonoSingleton.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using UnityEngine; | |
namespace LiquidPools { | |
/// use | |
/// public class NewClass : MonoSingleton<NewClass> { } | |
[DefaultExecutionOrder(-999)] | |
public abstract class MonoSingleton<T>: MonoBehaviour where T: MonoSingleton<T> { | |
public enum MonoSingletonDuplicateBehaviour { | |
DestroyOldInstance, | |
DestroyNewInstance, | |
DisableOldInstance | |
}; | |
public MonoSingletonDuplicateBehaviour duplicateBehavior = MonoSingletonDuplicateBehaviour.DestroyOldInstance; | |
public static string GameObjectName { | |
get { | |
return Instance.gameObject.name; | |
} | |
} | |
private static T _instance; | |
public static bool IsInstanced { | |
get { | |
return _instance != null; | |
} | |
} | |
public static T Instance { | |
get { | |
return _instance; | |
} | |
private set { | |
_instance = value; | |
} | |
} | |
protected void Awake() { | |
if (Instance!=null) { | |
Debug.LogError($"MonoSingleton An instance of {Instance.GetType().ToString()} already exists named {Instance.gameObject.name}; {duplicateBehavior}", Instance); | |
switch(duplicateBehavior) { | |
case MonoSingletonDuplicateBehaviour.DestroyOldInstance: | |
Destroy(Instance.gameObject); | |
break; | |
case MonoSingletonDuplicateBehaviour.DestroyNewInstance: | |
Destroy(this.gameObject); | |
return; | |
case MonoSingletonDuplicateBehaviour.DisableOldInstance: | |
Instance.gameObject.SetActive(false); | |
break; | |
default: | |
break; | |
} | |
//return; | |
} | |
Debug.Log($"MonoSingleton<{typeof(T)}> Awake named {gameObject.name}", this); | |
Instance = (T)this; | |
AfterAwake(); | |
} | |
protected void OnDestroy() { | |
Debug.Log($"MonoSingleton<{typeof(T)}> Destroying {gameObject.name}", this); | |
Instance = null; | |
AfterOnDestroy(); | |
} | |
/// Override this method to implement Awake functionality | |
protected virtual void AfterAwake() { | |
} | |
/// Override this method to implement OnDestroy functionality | |
protected virtual void AfterOnDestroy() { | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment