Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- /// <summary>
- /// A PartialMonoSingleton is like a MonoSingleton except simpler: It doesn't create itself if Instance is called and it doesn't exist.
- /// Instead it will return null.
- /// It still uses up the Awake and OnDestroy events so subclasses need to implement SubclassAwake or SubclassOnDestroy if they want to use those
- /// </summary>
- /// <typeparam name="T"></typeparam>
- public abstract class PartialMonoSingleton<T> : MonoBehaviour where T : PartialMonoSingleton<T> {
- // Query this to see if the singleton has been instantiated anywhere
- // NOTE: Static field in generic type - the value will be different for each inheritance of MonoSingleton
- public static bool Exists = false;
- public static T Instance = null;
- // Assign if this is the first instance, else just show a warning that we have more than one
- public void Awake() {
- if (Instance == null) {
- Instance = this as T;
- if (Instance != null) {
- Exists = true;
- Instance.SubclassAwake();
- }
- else {
- Debug.LogError("PartialSingleton could not assign the instance of this class (" + typeof(T) + ")");
- }
- }
- else {
- Debug.LogWarning("Multiple instances of the PartialSingleton class " + typeof(T) + " created.");
- }
- }
- protected void OnDestroy() {
- if (Instance != null) Instance.SubclassOnDestroy();
- Instance = null;
- Exists = false;
- }
- // Substitute for Awake() in implementing classes
- protected virtual void SubclassAwake() { }
- // Substitute for OnDestroy() in implementing classes
- protected virtual void SubclassOnDestroy() { }
- }
Add Comment
Please, Sign In to add comment