Skip to content

Instantly share code, notes, and snippets.

@fguillen
Last active February 18, 2022 12:21
Show Gist options
  • Save fguillen/a929a1d003a20bc727d8efe228b5dda4 to your computer and use it in GitHub Desktop.
Save fguillen/a929a1d003a20bc727d8efe228b5dda4 to your computer and use it in GitHub Desktop.
Singleton Scriptable Object for Unity
using UnityEngine;
// From here: https://www.youtube.com/watch?v=6kWUGEQiMUI&ab_channel=whateep
// Use it:
// 1) Create a subclass:
// public class MySingletonSO : SingletonScriptableObject<MySingletonSO> {}
// 2) Create the new Asset into the /Assets/Resources folder
// 3) Access to it:
// MySingletonSO.Instance
//
public abstract class SingletonScriptableObject<T> : ScriptableObject where T : SingletonScriptableObject<T>
{
static T instance;
public static T Instance
{
get
{
if (instance == null)
{
T[] assets = Resources.LoadAll<T>("");
if(assets == null || assets.Length < 1)
{
throw new System.Exception($"Not found Singleton Scriptable Object of type: {typeof(T).ToString()}");
} else if (assets.Length > 1)
{
throw new System.Exception($"More than 1 instance of Singleton Scriptable Object of type: {typeof(T).ToString()} found");
}
instance = assets[0];
}
return instance;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment