What is a ScriptableObject

A ScriptableObject is basically a standard class that you can create a 'new' of in-editor, have it serialized, and save it as an asset for later use. It also has some Monobehaviour-style callbacks like OnEnable() and OnValidate(). Other than that, it doesn't really differ from a basic c# class. You can put any amount of logic you want in it; not just 'data'.

'CreateInstance' and 'Instantiate'

There are two different ways to instantiate a ScriptableObject:

  • 'CreateInstance' is for when you want to create a "new" of the ScriptableObject class, with all the default parameters. It's like writing "new MyScriptableObject()"
  • 'Instantiate(myScriptableObject)' is for when you want to create an instance/clone of an existing ScriptableObject, with all of its serialized fields copied too. It works exactly like spawning a prefab, but with an .asset instead.

How ScriptableObjects help save memory

Suppose you have 50 'Health Potion' items currently spawned in your game, and that your 'Item' script has a reference to the image/sprite of that item when it's in your inventory. This means that the texture asset of the inventory image (and every other serializable parameters of that Monobehaviour) is copied 50 times in memory. (Source here). Instead, what you should do is have all your 'Items' reference a ScriptableObject that contains all the inventory images of all items, and get the texture from there. That way, there is only one copy of the texture asset in memory.

In short; ScriptableObjects allow you to put all the data in one place and have it referenced by everyone, instead of having it be duplicated by everyone.

Other uses

ScriptableObjects should also be used for representing entities that aren't necessarily tied to visuals at all times in the game. If we continue with the Health Potion & inventory example; it would be a great idea to have you entire 'Item' script be a ScriptableObject, and only make the prefabs of the items have a 'Pickable' script that references the 'Item' ScriptableObject associated with it. This way, when you pick up the item, you can only add its 'Item' ScriptableObject to the inventory, and completely destroy the prefab. Depending on the needs of the game, this can be a much more elegant/efficient method than storing the item GameObjects somewhere in the hierarchy and have them disabled.

ScriptableObjects are also great to create 'pluggable and configurable behaviours'. For example, you could create an 'AI' ScriptableObject that you create several variants of (each with their own parameters). Then, your 'Enemy' script would have a reference to its AI asset, which will inform it of how it should behave. This also means you can easily change its behaviour on-the-fly.

More examples here: https://www.youtube.com/watch?v=6vmRwLYWNRo

results matching ""

    No results matching ""