Cultivate: Before Time Dev Blog #6 – Scriptable Objects

This post is aimed at coders – it probably won’t make much sense if you’re not a programmer.

 

When designing the coding architecture for Cultivate, I decided Unity’s Scriptable Objects were the way to go for several parts of the project. ScriptableObject is a class your classes can inherit from. They create objects that Unity originally designed to store large quantities of data to be shared between MonoBehaviours.

 

For example, if you have a prefab with a script attached to it that contains a large list of strings, and then instantiate 5 game objects, you’ll have 5 copies of that list of strings – one for each game object. The larger the list and the more game objects you instantiate, the more memory this will take up. This is where Scriptable Objects come in – rather than having a copy of that data in every game object, the prefab’s script could have a reference to a Scriptable Object with that list in it. This would mean just a single copy of the list of strings exists, taking up a much more reasonable amount of memory!

 

In Cultivate, I used Scriptable Objects in another way – as a pluggable dataset. The plants in Cultivate all use the same basic game object – they have a Sprite Renderer and a MonoBehaviour script with a slot for a Scriptable Object. The Scriptable Object contains information like the plant’s sprites for different stages of growth, their growing period, climate information, etc. Adding the CreateAssetMenu class attribute:

[CreateAssetMenu(menuName = “Cultivate/Items/Plantable”)]

to the top of the class file, I can create new Plant Scriptable Objects through Unity’s menus: Create -> Cultivate -> Items -> Plantable.

Plantable Scriptable Object Context menu

 

I can make a carrot, for example, and then fill in the data:

Plantable Carrot Scriptable Object

 

The Scriptable Object also contains various methods that are called through the MonoBehaviour script.

I’m planning to use Scriptable Objects in other parts of the project too: pluggable AI behaviour for NPCs (non-player characters), pluggable farming tools, and pluggable inventory items.

 

Hopefully this post has shown that Scriptable Objects are really useful! There are some good YouTube videos that talk about this more: Unite 2016 – Overthrowing the MonoBehaviour Tyranny in a Glorious Scriptable Object Revolution and the playlist Pluggable AI With Scriptable Objects were really helpful.

Bookmark the permalink.

Leave a Reply