0
0
Unityframework~5 mins

Prefabs and reusable objects in Unity

Choose your learning style9 modes available
Introduction

Prefabs let you save a game object setup once and reuse it many times. This saves time and keeps your game organized.

You want to create many copies of the same enemy with the same settings.
You need to spawn objects like bullets or coins during gameplay.
You want to update all copies of an object by changing just one prefab.
You want to keep your scene clean by reusing objects instead of duplicating them.
You want to share objects between different scenes easily.
Syntax
Unity
1. Create a GameObject in the scene.
2. Drag the GameObject from the Hierarchy to the Project window to make it a Prefab.
3. To use the Prefab, drag it from the Project window back into the scene or instantiate it via script:

Instantiate(prefabReference, position, rotation);

Prefabs are stored in the Project window as assets.

You can edit a Prefab and all instances update automatically.

Examples
This script spawns an enemy prefab at the origin.
Unity
// Create a prefab reference
public GameObject enemyPrefab;

// Spawn an enemy at position (0,0,0) with no rotation
Instantiate(enemyPrefab, new Vector3(0, 0, 0), Quaternion.identity);
This creates an instance of the prefab in your scene without code.
Unity
// Drag a prefab into the scene manually
// Just drag the prefab from Project window into the Hierarchy or Scene view
Sample Program

This script spawns 5 coin prefabs spaced 2 units apart along the x-axis when the game starts.

Unity
using UnityEngine;

public class SpawnCoins : MonoBehaviour
{
    public GameObject coinPrefab;
    public int coinCount = 5;

    void Start()
    {
        for (int i = 0; i < coinCount; i++)
        {
            Vector3 position = new Vector3(i * 2.0f, 0, 0);
            Instantiate(coinPrefab, position, Quaternion.identity);
        }
    }
}
OutputSuccess
Important Notes

Always assign your prefab reference in the Inspector before running the game.

Changes to a prefab asset update all instances unless overridden locally.

Use prefabs to keep your project organized and efficient.

Summary

Prefabs save game objects for reuse.

They help spawn many copies easily.

Editing a prefab updates all its instances.