Skip to content

Instantly share code, notes, and snippets.

@James-Frowen
Created February 15, 2018 13:32
Show Gist options
  • Save James-Frowen/db46e7b3ed38c557d51f65643a1882f5 to your computer and use it in GitHub Desktop.
Save James-Frowen/db46e7b3ed38c557d51f65643a1882f5 to your computer and use it in GitHub Desktop.
Weird implementation of Singleton for ScriptableObjects
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