Singleton ScriptableObject #MadeWithUnity

GilbertoBitt
3 min readJul 25, 2018

Singleton Design Pattern combined with the power of Unity’s Scriptable Objects.

1- Singleton? wtf is that?

Singleton is a Design Pattern that restrict the intantiation of a class creating a way that garantee that only 1 instance of this class will ever be create.

Intent:

- Ensure a class has only one instance, and provide a global point of access to it.

- Encapsulated “just-in-time initialization” or “initialization on first use”.

2- Understand what is ScriptableObject create for:

According to unity manual/documentation scriptableObject is described as:

class that allows you to store large quantities of shared data independent from script instances.

Also According to Unity

The intended use case for using ScriptableObject is to reduce memory usage by avoiding copies of values, but you could also use it to define pluggable data sets.

So.. we can use has a file do save configuration, item database, npc behavior or just dialog or inventory.

in my example imagine i want to create a inventory to my single player game. i don’t need my game have more than 1 inventory created and i want to make sure i will have just only 1 instance of PlayerInventory so for that case i will use singleton design pattern combined with ScriptableObject!

But first lest start creating the SingletonScriptableObject class, here is the code:

SingletonScriptableObject Source Code

I hope u understand what is inside soon i will put comments of the code itself to better understand of each line for now let’s continue.

Now we need like always create a scriptableObject script but instead of using scriptableObject we will use SingletonScriptableObject like above:

PlayerInventory (ScriptableObject) Has SingletonScriptableObject

Now we need create a instance of it

PS: i didn’t create a way to force creation of just one .asset file so to make sure use t:PlayerInventory on search box inside the Project Window to make sure you will have only one in the entire project.

now lets add some value to the PlayerInventory.Asset file.

Here is my PlayerInventory Asset look like.

now lets build the script that will use it.

Exemple of how to use/call the singleton instance of ScriptableObject

Now lets just test to see if everything works fine.

Just add the PlayerInventoryReader to the camera on a empty scene and hit play and check it out the Console to see if everything works like a charm you will be able even to see the reference on the inspector to the PlayerInventory Asset file.

The Debug Log output
Reference of Player Inventory Asset File on Inspector.

Has you can see we can build many things, i use this Singleton Design Pattern to create ScriptableObject responsibles for many things like Sound Manager, Global Configuration and others things… I hope you guys like it.

Next: ScriptableObject Variables (Comming Soon).

--

--