Scriptable Objects have 2 major uses

  1. Saving and storing data during an editor session
  2. Saving data as an asset in our project for use at runtime

Things to Note

  1. In the editor we can save data to the SO during edit and runtime
  2. In a deployed build we can only read the data from the SO, we cannot save to it. – so no good for saving game state data.

So what’s good about Scriptable Objects

So you can make your scriptable object an Asset and create one in your Project panel with the “Create” menu. You can also define the name of your scriptable object as it appears in the create menu.

Adding your Scriptable Object to the Unity “Create” menu

 [CreateAssetMenu(menuName = "Scriptable Objects/YourObjectName", fileName = "YourObjectName.asset")]

Now once you have created your scriptable object asset, it’s public properties will be available in the inspector simply by selecting it in your project panel. You don’t need to attach it to a scene gameobject in order to be able to view and edit the data.

Why not just use a class?

Well yes you could, but using a scriptable object to store unchanging game data is probably the most efficient way. It creates just one set of data that remains constant, and everything in your file can access this one copy, rather than creating an instance of the data for every gameobject that uses it.

 

Serialization of Scriptable Objects

Two important attributes to know about

System.Serializable

System.SerializeField

Classes and struct need to be [Serializable]. All public fields are then serialized. Add it above the class definition.

[System.Serializable]
public class MyScriptableObject : ScriptableObject

In Unity, the [SerializeField]  attribute allows you to have private script variables that are exposed in the Inspector. This will let you set the values in the editor without giving access to the variable from other scripts.