Skip to content

Instantly share code, notes, and snippets.

@Oxeren
Last active February 15, 2024 04:57
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Oxeren/63f970cf92a752f9d72d6cea4b35b2b1 to your computer and use it in GitHub Desktop.
Save Oxeren/63f970cf92a752f9d72d6cea4b35b2b1 to your computer and use it in GitHub Desktop.
Auto singleton Unity ScriptableObject. Derive your class from this class (and use your class as the generic type), create an instance in the Resources folder (name of the instance must be the same as the name of your class). Then you will be able to access the singleton via static Instance property without having to add boilerplate code.
// Example Scriptable Object. Instance must be placed in Resources folder and have the same name as the class, type of generic parameter must be your class.
using UnityEngine;
[CreateAssetMenu(fileName = "MySingletonSO")]
public class MySingletonSO : SingletonScriptableObject<MySingletonSO>
{
// Here goes your data. This class can be called by the static Instance property, which will automatically locate the instance in the Resources folder.
}
using UnityEngine;
public abstract class SingletonScriptableObject<T> : ScriptableObject where T : ScriptableObject
{
static T instance;
public static T Instance {
get {
if (instance == null)
{
instance = Resources.Load<T>(typeof(T).ToString());
(instance as SingletonScriptableObject<T>).OnInitialize();
}
return instance;
}
}
// Optional overridable method for initializing the instance.
protected virtual void OnInitialize() { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment