Course contentsShow
← Unity Game Development
Lesson 90 of 8282. Scripting and LifecycleFree lesson

Sharing Data Through ScriptableObjects

Use ScriptableObjects as a centralized data container to allow multiple independent GameObjects to access and modify shared game state information efficiently.

In this lesson, you will learn how to use ScriptableObjects to create a shared "data hub" that allows independent GameObjects to read and modify the same information without needing direct references to each other.

The Problem with Direct References

Up until now, if you wanted two objects to share a value—like a score or playerHealth—you might have used a Singleton or manually dragged references in the Inspector. This becomes messy as your game grows. If you have ten enemies that all need to know the player’s health, linking them all is a nightmare.

The ScriptableObject Solution

Think of a ScriptableObject as a "data file" that lives in your Project folder rather than just inside a specific scene. Because it is a file (an asset), any script in your project can point to it. When one object changes a value inside that file, every other object looking at that same file sees the update instantly.

To create one, you define a class that inherits from ScriptableObject rather than MonoBehaviour:

using UnityEngine;

[CreateAssetMenu]
public class GameData : ScriptableObject
{
    public int currentScore;
}

By adding [CreateAssetMenu], you can right-click in your Project window and create a new instance of this data file.

Putting It Into Action

Now, you can create a field in your Player script and your UIManager script that points to this specific asset file:

public GameData sharedData; // Drag your file here in the Inspector

void Update() 
{
    // The player modifies the shared data
    sharedData.currentScore += 10;
}

Because both the Player and the UIManager reference the exact same file asset, the UI will always display the most current score without the two scripts ever having to "talk" to each other directly. This decouples your systems, making your code much cleaner and easier to debug.

Key Takeaway: ScriptableObjects act as a centralized data container, allowing independent GameObjects to share and synchronize state by pointing to the same external asset file.