Introduction
Prefabs let you save a game object setup once and reuse it many times. This saves time and keeps your game organized.
Prefabs let you save a game object setup once and reuse it many times. This saves time and keeps your game organized.
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.
// 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);
// Drag a prefab into the scene manually // Just drag the prefab from Project window into the Hierarchy or Scene view
This script spawns 5 coin prefabs spaced 2 units apart along the x-axis when the game starts.
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); } } }
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.
Prefabs save game objects for reuse.
They help spawn many copies easily.
Editing a prefab updates all its instances.
public GameObject prefab;
void Start() {
GameObject obj = Instantiate(prefab);
Debug.Log(obj.name);
}public GameObject prefab;
void Start() {
GameObject obj = Instantiate(prefab, new Vector3(0, 0, 0));
}Pass the test and this pattern moves unknown