Created
February 15, 2018 13:32
-
-
Save James-Frowen/db46e7b3ed38c557d51f65643a1882f5 to your computer and use it in GitHub Desktop.
Weird implementation of Singleton for ScriptableObjects
This file contains 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 UnityEngine; | |
namespace JamesFrowen.Variables | |
{ | |
public abstract class SingletonScriptableObject<T> : ScriptableObject where T : ScriptableObject | |
{ | |
protected static T _instance; | |
public static T Instance | |
{ | |
get | |
{ | |
if (_instance == null) | |
{ | |
_instance = FindObjectOfType<T>(); | |
if (_instance ==null) | |
{ | |
_instance = CreateInstance<T>(); | |
} | |
} | |
return _instance; | |
} | |
protected set | |
{ | |
if (_instance !=null) { Debug.LogWarning("overriding singleton instance"); } | |
_instance = value; | |
} | |
} | |
protected virtual void OnEnable() | |
{ | |
if (_instance == null) | |
{ | |
_instance = (T)(ScriptableObject)this; | |
} | |
else if (_instance != this) | |
{ | |
Destroy(this); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment