How to use ScriptableObjects in Unity?

Ouzani Abd Raouf
3 min readJun 26, 2020

A ScriptableObject is a data container that you can use to save large amounts of data, independent of class instances.

Here are some elements to be considered when using ScriptableObjects :

- ScriptableObjects can considerably reduce your project’s memory usage by avoiding copies of values. For example, if your project has a Prefab that stores unchanging data in attached MonoBehaviour scripts, then every time you instantiate that Prefab, it will get its own copy of that data. Instead, you can use only one ScriptableObject to store the data and then access it by reference from all of the Prefabs.

- You cannot attach a ScriptableObject to a gameObject; you have to save them as “Assets” in your project.

- You can’t use ScriptableObjects to save data in a deployed build. In fact, you can only use the data saved during development.

Data saved in the Unity Editor to ScriptableObjects as an asset is written to disk and is therefore persistent between sessions.

Using a ScriptableObject

ScriptableObjects can be used to:

- Save and store data in the Editor;

- Save data as an Asset in your project to use at run time.

First, you need to create a script that inherits from the ScriptableObject class.

You can use the “CreateAssetMenu” attribute to create custom ScriptableObjects using your class. For example:

using UnityEngine;[CreateAssetMenu(fileName = "MyData", menuName = "ScriptableObjects/MyNewScriptableObject", order = 1)]public class CreateMyScriptableObject : ScriptableObject
{
public int myInt;
public string myString;
public Transform[] myTransformsArray;
}

As a result, in the “Assets/Create” context menu, you will have a menu item named “ScriptableObjects” with a submenu item named “MyNewScriptableObject”. When you click on this submenu, Unity will create a ScriptableObject file named “MyData” in your project.

Note that, as mentioned above, You cannot attach this script to a gameObject. You will have the following message if you try to do so :

You can now give your new ScriptableObject instance (file) a meaningful name and alter the values.

The next step is to use these values. You need to create a new script that references your ScriptableObject, in our example, a “CreateMyScriptableObject”. For example:

using UnityEngine;public class MyOtherScript : MonoBehaviour
{
// An instance of the ScriptableObject defined above.
public CreateMyScriptableObject MyData;
private int bestScore;
private string playerName;
private Transform currentGameObject;
void Start()
{
bestScore = MyData.myInt;
playerName = MyData.myString;
currentGameObject = MyData.myTransformsArray[0];
}

}

Now you can attach the above script to a GameObject in your Scene, then drag the “MyData” ScriptableObject that you have created to the correspondent field in the inspector.

Thank you for reading my article. If you like it, please share it.

See also :

--

--