Singleton ScriptableObjects
Published 5 months ago
How to set them up
Sometimes you need data that can be accessed from anywhere without an instance to a class, this is where the singleton comes into play. A singleton is a class that can only have one instance of itself running at a time and has a static reference to that instance. This way you can access that instance like this MySingletonClass.Instance. Look at the example below (an item database):
public class ItemsDB { private static ItemsDB instance; public static ItemsDB Instance { get {return instance; } } //We use a property so no one from outside can change the value of instance //We can make this field static so it's easier to access it public static List<Item> items = new List<Item>(); //Set instance variable upon creation public ItemsDB() { instance = this; } }
Ok, this is a singleton but we can't access it from the Editor, only from code, and that renders this particular class for this particular purpose useless. So we need a ScriptableObject.
public class ItemsDB : ScriptableObject { ...
Ok, so now we can create the it in the editor and it might work the way it is, setting instance in the constructor. But the best way to do initialize the class is through a static Init method with the [RuntimeInitializeOnLoadMethod] attribute that will load our scriptable object asset, like this:
[RuntimeInitializeOnLoadMethod] private static void Init() { instance = Resources.LoadAll<ItemsDB>()[0]; }
Add that to the class and when the game starts either in the editor or in a build, no matter what scene, all methods with the [RuntimeInitializeOnLoadMethod] attribute will be called, including our Init. In this method we will load the first asset of type ItemsDB Unity finds inside any Resources folder, so you need to place the scriptable object inside a Resources folder. If you have more than one ItemsDB in the Resources folder you should use Resources.Load<ItemsDB>("MyAssetPath"); instead.
That's it, we reached the end of this very short "tutorial" on singleton scriptable objects. I hope someone has learned something new with this article and if there are any alternatives to this method or if someone encounters any issues please let me know.

Self taught hobbyist - Programmer