In this lesson, you will learn how to use ScriptableObjects as centralized, persistent "data containers" to share primitive values across entirely unrelated game objects without needing complex references.
The Problem of Tight Coupling
Typically, if a PlayerHealth component needs to communicate with a UIHealthBar component, you might use GetComponent or serializing references in the Inspector. This creates tight coupling—if you move the UI or replace the player, your references break. ScriptableObject variables allow us to decouple these systems by letting them both "point" to the same data asset.
Creating the Shared Variable
Instead of storing a value inside a MonoBehaviour, we define a generic container using ScriptableObject.
[CreateAssetMenu(fileName = "NewFloatVariable", menuName = "Variables/Float")]
public class FloatVariable : ScriptableObject
{
public float Value;
}
By creating an instance of this asset in your project (e.g., PlayerHealthAsset), you can drag this single file into the Inspector of any script that needs it.
Why this is Powerful
- Persistent State: Because
ScriptableObjectsexist independently of the Scene, the data persists even when switching scenes or reloading levels. - Global Syncing: When the
PlayerHealthscript modifiesplayerHealthAsset.Value, every other script referencing that same asset—like aUIHealthBaror aDeathManager—sees the updated value instantly. - No Direct References: Your
UIHealthBarno longer needs to know that a "Player" exists. It only knows that it needs to display the value of theFloatVariableassigned to it.
Implementation Tip
When using this for gameplay, be aware that changes made to ScriptableObjects in the Editor persist after you stop playing. To prevent this, it is standard practice to implement an OnEnable method in your asset that resets the value to a DefaultValue variable, ensuring your game always starts with a fresh state.
Key Takeaway: By offloading primitive data into ScriptableObject containers, you create a "Source of Truth" that allows independent systems to sync state seamlessly without knowing about each other's existence.