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

Defining Data Containers with ScriptableObjects

Create custom asset classes that decouple static game data from individual GameObject instances to improve project organization.

In this lesson, you will learn how to use ScriptableObjects to create modular, reusable data containers that exist independently of your GameObjects.

The Problem with Component-Based Data

Up until now, you’ve likely stored data (like health values or movement speeds) directly inside MonoBehaviour scripts attached to your Prefabs. While this works, it creates a "tight coupling": if you want to update the stats for 50 different enemies, you have to open each Prefab and change the values manually. If you want a global change, you are stuck updating every instance.

The ScriptableObject Solution

A ScriptableObject is a specialized Unity class that allows you to store data in a separate "Asset" file in your Project window, rather than inside a Scene file. Because it is an asset, it can be referenced by any number of GameObjects. If you update the data in that asset file, every GameObject referencing it receives the update instantly.

Consider a simple ItemData container:

using UnityEngine;

[CreateAssetMenu(fileName = "NewItem", menuName = "Inventory/Item")]
public class ItemData : ScriptableObject
{
    public string itemName;
    public Sprite icon;
    public int goldValue;
}

By adding the [CreateAssetMenu] attribute, you can right-click in your Project window and create an instance of this data container just like you would create a new Material or Folder. You can create one ItemData asset called "Sword" and drag it into the inspector of any NPC or Loot Chest in your game.

Why This Matters

By moving your "static" data—the values that define what an object is—out of the Prefab's logic and into a ScriptableObject, you decouple your game balance from your object instances. This makes your project significantly easier to manage; you can tweak gameplay numbers in the Inspector without ever needing to open a Prefab or modify code. It keeps your Prefabs lean, focusing them solely on behavior (how they move or react) rather than state (the raw numbers they hold).

Key Takeaway: ScriptableObjects allow you to store game data in independent asset files, enabling you to share and update information across multiple Prefabs from a single, centralized source.