The messiah that is Scriptable Objects

Scriptable Objects have been around in Unity since 2012 with the release of Unity 4…wow that was a long time ago! Anyway these are pretty handy and I’m surprised by the amount of people I come across that either don’t know what they are, or how to use them.

Scriptable Objects are:

A class you can derive from if you want to create objects that don’t need to be attached to game objects.

This is most useful for assets which are only meant to store data.

– Unity Documentation

This is great as not everything needs to live in the scene! Some great examples include AI, Inventory and Save Files. Whilst its great that code can be run without the need to exist in the scene, they can also store data…data which persists through gameplay. Meaning that saving is as simple as changing existing variables in a scriptable object asset. This counts for both play mode in editor and for released gameplay.

To create a Scriptable Object, you need to create a C Sharp script that inherits from ‘ScriptableObject’ as opposed to the default ‘MonoBehaviour’. If you then want to easily create an asset of that scriptable object type then above the class definition you should add ‘[CreateAssetMenu(menuName=”myNewScriptbaleObject”)]’. There are also a few more additional parameters but that’s the base implementation to show in the context menu.

I should not that Awake, Start, Update, FixedUpdate, OnXXXXX functions aren’t called in this context. A way to get around this is to create your own OnUpdate(MonoBehvaviour callingClass). So in a normal MonoBehaviour will have its Update executing that block of code. This is how a pluggable AI system is created (much like the one in the Unity live training tutorials here)

If you wanted to create a scriptable object at run-time then you will need to use ScriptableObject.CreateInstance<MyScriptableObjectClass>(). This however isn’t saved without an additional save system to serialise out the asset yourself. It couldn’t be that simple!

Seriously though, if you can use Scriptbale Objects you should. They also make it simpler to control a bunch of gameplay features / objects with a small amount of effort.

Leave a Reply