ScriptableObjects are serialized objects that are not bound to scenes or gameobjects as MonoBehaviours are. To put it one way, they are data and methods bound to asset files inside your project. These ScriptableObject assets can be passed to MonoBehaviours or other ScriptableObjects, where their public methods can be accessed.
Due to their nature as serialized assets, they make for excellent manager classes and data sources.
Below is a simple ScriptableObject implementation.
using UnityEngine;
[CreateAssetMenu(menuName = "StackOverflow/Examples/MyScriptableObject")]
public class MyScriptableObject : ScriptableObject
{
[SerializeField]
int mySerializedNumber;
int helloWorldCount = 0;
public void HelloWorld()
{
helloWorldCount++;
Debug.LogFormat("Hello! My number is {0}.", mySerializedNumber);
Debug.LogFormat("I have been called {0} times.", helloWorldCount);
}
}
By adding the CreateAssetMenu
attribute to the class, Unity will list it in the Assets/Create submenu. In this case it's under Assets/Create/StackOverflow/Examples.
Once created, ScriptableObject instances can be passed to other scripts and ScriptableObjects through the Inspector.
using UnityEngine;
public class SampleScript : MonoBehaviour {
[SerializeField]
MyScriptableObject myScriptableObject;
void OnEnable()
{
myScriptableObject.HelloWorld();
}
}