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

Injecting Data Dependencies into Game Objects

Develop a reference pattern where prefabs pull their configuration from assigned ScriptableObject slots at runtime.

In this lesson, you will learn how to decouple your game logic from hard-coded values by injecting data directly into your GameObjects using ScriptableObject references.

The Problem: Hard-Coding vs. Dependency Injection

As your game grows, "hard-coding" variables—like health, movement speed, or damage values—directly inside your MonoBehaviour scripts makes your project rigid and difficult to balance. If you want to change the stats of an enemy, you shouldn't have to open the script, change a line of code, and recompile.

Instead, we use Dependency Injection. By creating a "slot" in your script for a ScriptableObject, you allow the GameObject to "pull" its configuration from an external data asset at runtime.

Implementing the Reference Pattern

Imagine you have an Enemy prefab. Instead of giving it a speed variable, you give it a reference to an EnemyData ScriptableObject.

public class EnemyController : MonoBehaviour
{
    // This is our injection slot
    public EnemyData enemyConfiguration;

    private void Start()
    {
        // The prefab pulls its settings from the assigned asset
        float speed = enemyConfiguration.moveSpeed;
        string enemyName = enemyConfiguration.displayName;
        
        Debug.Log($"Initialized {enemyName} with speed: {speed}");
    }
}

By assigning an EnemyData asset (created via ScriptableObject) to the EnemyConfiguration slot in the Inspector, your prefab now functions as a "shell" that behaves differently based on which data file it is fed.

Why This Matters for Prefabs

When you use this pattern, your Prefabs become highly flexible templates. You can create ten different variations of an enemy (e.g., "Fast Scout," "Heavy Tank," "Boss") simply by creating ten different EnemyData assets. You drag your "Fast Scout" asset into the EnemyConfiguration slot on one prefab instance, and your "Heavy Tank" asset into another.

The logic stays identical (EnemyController), but the identity of the GameObject changes instantly. This separation keeps your code clean and makes your game world much easier to balance, as you can tweak the asset files while the game is running without touching the Prefab or the C# scripts themselves.

Key Takeaway: By injecting ScriptableObjects into your prefabs, you transform rigid scripts into flexible, data-driven systems that are easy to configure, test, and balance.