In this lesson, you will learn how to trigger the creation of game objects from your Prefab assets at runtime using C# scripting.
Spawning with Instantiate
Up until now, we have manually placed Prefabs into the Scene view. However, many gameplay scenarios—like firing projectiles, spawning enemies, or dropping loot—require creating objects dynamically while the game is running. In Unity, we use the Instantiate method to clone a Prefab asset and place it into the active Scene hierarchy.
When you call Instantiate, Unity takes your source Prefab, duplicates its entire nested hierarchy, preserves its configured components (like Rigidbody or Collider), and initializes it in the game world.
Basic Implementation
To spawn an object, you first need a reference to the Prefab asset. You can expose this in your script using a public or [SerializeField] variable.
using UnityEngine;
public class Spawner : MonoBehaviour
{
// Drag your Prefab asset into this slot in the Inspector
public GameObject objectToSpawn;
void Start()
{
// Creates a new instance of the Prefab at the origin
Instantiate(objectToSpawn);
}
}
Preserving Hierarchy and Transforms
By default, Instantiate places the object at the world origin with its original rotation. If your Prefab has a complex nested hierarchy (for example, a character with an attached camera and particle system), Instantiate keeps that structure intact, ensuring the parent-child relationships remain exactly as they were defined in the Prefab asset.
If you want to spawn an object at a specific position, you can pass a Vector3 position and Quaternion rotation to the method:
// Spawns the object at this transform's position and rotation
Instantiate(objectToSpawn, transform.position, transform.rotation);
Because this new object is a clone, any modifications you make to its components via script—such as adding an impulse force to its Rigidbody—will only affect that specific instance, leaving your source Prefab asset untouched. This allows you to maintain clean, modular templates while populating your game world with diverse, interactive instances.
Key Takeaway: The Instantiate method allows you to generate runtime copies of your Prefab assets, perfectly preserving their component configurations and nested hierarchies for use in dynamic gameplay systems.