Last active
February 15, 2024 04:57
-
-
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.
This file contains hidden or 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
// 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. | |
} |
This file contains hidden or 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; | |
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