Course contentsShow
← Unity Game Development
Lesson 246 of 8284. Prefabs and Data ManagementFree lesson

Creating Runtime Data Overrides

Implement logic to modify ScriptableObject data during gameplay while ensuring the original source assets remain unchanged for future sessions.

In this lesson, you will learn how to modify ScriptableObject data during gameplay without accidentally overwriting your original project files.

The Problem with Direct Modification

As you’ve learned, ScriptableObject assets are saved as files in your Project folder. If you modify a property on a ScriptableObject while in Play Mode, Unity saves that change directly to the asset. This is often dangerous; if you adjust a character’s "Base Health" to test balance, you don't want that change to persist permanently, as it will ruin the default values for the next session.

The Solution: Runtime Instance Cloning

To safely modify data during runtime, we use the Instantiate() method. When you call Instantiate() on a ScriptableObject, Unity creates a unique, in-memory copy of that object. This "clone" behaves exactly like the original, but it exists only for the duration of the current session. Any changes you make to this copy will never touch the source asset in your Project folder.

Here is how you implement this:

public class EnemyController : MonoBehaviour
{
    public EnemyStats originalStats; // The asset in your Project folder
    private EnemyStats runtimeStats; // The unique copy for this instance

    void Awake()
    {
        // Create an in-memory clone of the data
        runtimeStats = Instantiate(originalStats);
    }

    public void ApplyDamageModifier(float multiplier)
    {
        // Only the clone is modified; the original asset remains untouched
        runtimeStats.health *= multiplier;
    }
}

Why This Matters

By creating a runtime instance, you gain the freedom to experiment. You can have ten enemies in your scene, each with its own runtimeStats clone. One enemy might be buffed, another debuffed, and a third left at default values—all while sharing the same source asset structure. When you stop Play Mode, these temporary clones are destroyed by the garbage collector, and your original ScriptableObject assets remain exactly as you configured them in the Editor.

Key Takeaway: Always use Instantiate() when you need to modify a ScriptableObject at runtime to ensure your source assets remain pristine and unchanged for future play sessions.