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

Referencing ScriptableObjects in MonoBehaviour Scripts

Assign data assets to serialized fields in your components to access shared configuration values at runtime efficiently.

In this lesson, you will learn how to connect your ScriptableObject data assets directly to your MonoBehaviour components to create a clean, centralized data management system.

The "Data-Driver" Concept

Previously, we learned how to create ScriptableObject assets to act as data containers (like PlayerStats or ItemDefinitions). While these files sit safely in your Project window, they are invisible to your game objects until you explicitly link them. By creating a serialized field in a MonoBehaviour, you allow your game objects to "plug in" these assets, enabling them to read shared configuration values at runtime without needing to store that data locally in every single prefab.

How to Implement the Link

To link a ScriptableObject, you treat it just like any other reference (like a Transform or a Material). Simply declare a public or [SerializeField] variable in your script using the specific class name of your data container.

Here is an example using a PlayerStats ScriptableObject:

using UnityEngine;

public class PlayerController : MonoBehaviour
{
    // By declaring this, Unity creates an empty slot in the Inspector
    [SerializeField] private PlayerStats playerSettings;

    private void Start()
    {
        // Access data directly from the ScriptableObject asset
        float moveSpeed = playerSettings.movementSpeed;
        Debug.Log("The player speed is: " + moveSpeed);
    }
}

Why This Workflow Matters

Once this code is compiled, you will see a slot labeled "Player Settings" in your component’s Inspector. You can drag your PlayerStats asset from the Project window into that slot.

The major benefit here is Shared Configuration. If you have 50 enemy prefabs all referencing the same EnemyData asset, you don't need to manually update 50 prefabs to change a value. You simply edit the single ScriptableObject file, and every component referencing it will instantly reflect the new data. This keeps your project modular, prevents duplicate data bloat, and makes balancing your game significantly faster.

Key Takeaway: By using serialized fields to reference ScriptableObjects, you decouple your game logic from your data, allowing you to manage shared settings globally through central assets rather than individual prefab overrides.