ScriptableObjects

What are they and how does Total AI use them?


A ScriptableObject (SO) is a Unity class that allows Unity to create an instance of the class and save it as an asset. This asset can then be referenced by Components or by other ScriptableObject assets. This makes it perfect for storing data but also excellent for custom logic.

Logic configuration can be done by creating a superclass (parent class) that is referenced in other SOs or Components and then the subclass instances (SO Assets) are the ones actually plugged into the field in the Editor. For example, InputConditionType (ICT) is the superclass that all other ICTs inherit from. The ICT class defines the core methods an ICT class must implement. This pattern is repeated all over TAI as it provides a perfect method for plug and play customization.

Data


The common use case for Unity's ScriptableObjects is to store data. Each ScriptableObject asset can be be referenced by many Components, thus saving significant space. The Unity Manual page for ScriptableObject gives a good explanation of this.

Logic


If SOs are great for storing data why not also logic? One reason logic isn't mentioned as much as it is a bit more complicated than storing data. To store logic a base class that inherits from ScriptableObject needs to be created with all of the required method signatures defined. Then the custom logic will reside in the class that inherits from this base class by overriding the required methods. The actual SO asset has to be created from this new class. If the new class has member variables, multiple SO assets could be created with different variable values. (Now it's storing data and logic.) A couple of examples will make this more concrete.

Input Condition Types (ICTs) make use of this pattern. The ICT base class inherits from ScriptableObject and is abstract, which means it can't be instantiated and all of its abstract methods must be implemented in classes that inherit from it. ICT only has one abstract method Check. TAI ships with many ICTs but one commonly used one is ItemAmountICT.

The final step is to create the SO asset for the ItemAmountICT. Since ItemAmountICT has no member variables, only one SO asset should be created for it. This asset can now be plugged into any Input Condition because InputCondition has a InputConditionType field.

Target Factors also follow this pattern but tend to have member variables associated with them unlike ICTs. The same pattern would be followed for ICT except multiple SO assets would be created for each of the member variable settings.

Videos on SOs


There are some great Unity Unite talks on SscriptableObjects and checkout more links in More Resources.