Skip to content

Unity Instantiate: How to Create GameObjects at Runtime in Unity

Unity Instantiate: How to Instantiate GameObjects at Runtime in Unity

Table of Contents

Imagine you’re developing a shooting game. The player fires a weapon, bullets fly across the screen, enemies appear from different directions, and explosions occur whenever something gets destroyed. But have you ever wondered how Unity creates all these objects while the game is running? The answer is Unity Instantiate, a powerful method that allows you to create GameObjects dynamically during gameplay.

Unity Instantiate: How to Create GameObjects at Runtime in Unity

You don’t need to place every bullet, enemy, explosion, or collectible manually inside your scene. Instead, you can create them whenever they’re needed using Unity’s Instantiate() method. This makes it easier to build dynamic gameplay systems where objects appear, disappear, and interact based on player actions or game events.

Whether you’re building a 2D platformer, a 3D adventure, a tower defense game, or a multiplayer experience, understanding Unity Instantiate is an essential skill. It helps you spawn objects from Prefabs, control their position and rotation, and create gameplay elements at runtime.

In this tutorial, you’ll learn how Unity Instantiate works through practical C# examples. We’ll cover how to instantiate GameObjects, spawn multiple objects, set their position and rotation, use Prefabs, and manage runtime object creation without hurting game performance.

What Is Instantiate in Unity?

In Unity, Instantiate() is a method used to create a copy of an existing object during runtime. It creates a new instance of the original GameObject and adds it to the scene.

Think of it as using the Duplicate command in the Unity Editor, except you’re doing it through C# code while the game is running.

For example, imagine you have an enemy Prefab in your Project window. Instead of manually placing ten enemies in your level, you can use Instantiate to create as many copies as your gameplay requires.

The original object remains unchanged. Unity creates a separate copy that can move, interact with other objects, take damage, and perform its own gameplay logic.

Here are some common situations where you might use Instantiate:

  • Creating bullets when the player fires a weapon.
  • Spawning enemies during different waves.
  • Creating coins, health packs, and other collectibles.
  • Generating particle effects and explosions.
  • Creating new characters or NPCs.
  • Generating objects dynamically in procedural levels.
  • Displaying damage indicators and floating text.

In short, whenever your game needs to create a new GameObject while running, Instantiate is one of the first methods you should consider.

Why Do We Need to Create GameObjects at Runtime?

You might be thinking: why not simply create all the objects inside the scene before starting the game?

That approach works for simple projects, but it quickly becomes difficult to manage when your game contains dynamic gameplay.

Consider a shooting game where a player can fire hundreds of bullets. Would you manually place every bullet in the scene? Obviously not.

Instead, you create a bullet Prefab and instantiate a new bullet whenever the player fires.

Runtime object creation provides several advantages:

1. Dynamic Gameplay

Objects can appear based on player actions, game events, timers, or random conditions.

For example, in a survival game, you can spawn enemies every few seconds. As the player progresses, you can increase the number of enemies or introduce stronger enemy types.

2. Reusable GameObjects

You can create one Prefab and use it in multiple locations throughout your game. There is no need to manually configure the same object repeatedly.

3. Easier Scene Management

Instead of filling your scene with hundreds of objects that may not even be needed, you can create them only when required.

4. More Gameplay Possibilities

Runtime instantiation makes many gameplay systems possible, including:

  • Enemy wave systems.
  • Random item generation.
  • Procedural level generation.
  • Dynamic environment objects.
  • Weapon firing systems.
  • Runtime visual effects.

How to Use Instantiate in Unity with C#

Now let’s understand how to use Instantiate in a real Unity project.

Before writing the script, you need a GameObject that Unity can duplicate. Although you can instantiate existing scene objects, using a Prefab is generally the better approach for reusable runtime spawning.

Step 1: Create a Prefab

First, create a GameObject that you want to spawn.

  1. Open your Unity project.
  2. Create a new GameObject, such as a Cube or Sphere.
  3. Configure its Transform, Material, Collider, and other required components.
  4. Drag the GameObject from the Hierarchy into the Project window.
  5. Unity will create a Prefab asset.
  6. You can now delete the original scene object if you don’t need it.

Your Prefab is now ready to be instantiated through a C# script.

Step 2: Create an Instantiate Script

Create a new C# script named SpawnExample.cs and attach it to an empty GameObject in your scene.

Let’s start with the simplest example:

using UnityEngine;

public class SpawnExample : MonoBehaviour
{
    public GameObject prefab;

    void Start()
    {
        Instantiate(prefab);
    }
}

When you run the game, Unity creates a copy of the assigned Prefab.

Let’s understand what’s happening:

  • public GameObject prefab; creates a reference that allows you to assign a Prefab through the Inspector.
  • Start() executes when the script is initialized.
  • Instantiate(prefab); creates a new copy of the assigned GameObject.

One important thing to remember: when you use this overload without specifying a position, Unity uses the original object’s Transform values for the clone. It does not automatically place the object at the spawner’s position.

To spawn objects at a specific location, provide a position and rotation explicitly.

Step 3: Assign the Prefab in the Inspector

  1. Select the GameObject containing SpawnExample.
  2. Locate the Prefab field in the Inspector.
  3. Drag your Prefab from the Project window into that field.
  4. Press Play.

Unity will now create an instance of your Prefab when the game starts.

Tip: Always check your Inspector references before running the game. If the Prefab field is empty, Unity will throw an exception when you try to instantiate it.

How to Instantiate a GameObject at a Specific Position and Rotation

Creating an object is only half the job. In most games, you also need control over where that object appears and which direction it faces.

For example:

  • A bullet should appear at the weapon’s muzzle.
  • An enemy should spawn at a designated location.
  • A collectible should appear where an enemy was defeated.
  • An explosion should appear at the collision point.

Unity provides an overload of Instantiate that accepts three important parameters:

Instantiate(prefab, position, rotation);
  • prefab: The GameObject you want to duplicate.
  • position: The world position where the new object should appear.
  • rotation: The world rotation of the new object.

Example: Spawn an Object Using a Spawn Point

Let’s create a simple spawning system using a Transform as the spawn location.

using UnityEngine;

public class SpawnExample : MonoBehaviour
{
    public GameObject prefab;
    public Transform spawnPoint;

    void Start()
    {
        Vector3 spawnPosition = spawnPoint.position;
        Quaternion spawnRotation = spawnPoint.rotation;

        Instantiate(prefab, spawnPosition, spawnRotation);
    }
}

In this example, the spawned object appears at the position and rotation of the assigned spawnPoint.

How to set it up:

  1. Create an empty GameObject in your scene.
  2. Rename it SpawnPoint.
  3. Move it to the location where you want the object to appear.
  4. Assign the Prefab and SpawnPoint in the Inspector.
  5. Run the game.

This approach is particularly useful for enemy spawning, projectile systems, and object generation.

What Is Quaternion.identity in Unity Instantiate?

You will frequently see Quaternion.identity when working with Instantiate.

It represents a rotation with no rotation applied (0 degrees of rotation).

Instantiate(prefab, transform.position, Quaternion.identity);

This creates the Prefab at the current GameObject’s world position without applying any additional rotation.

If you want the spawned object to face the same direction as the spawner, you can use:

Instantiate(prefab, transform.position, transform.rotation);

This is especially useful when spawning bullets, missiles, or characters that need to inherit the direction of another object.

How to Instantiate Multiple GameObjects in Unity

Sometimes you need to spawn several objects at once instead of creating just one.

For example, you might want to generate ten coins, create an enemy wave, or distribute objects across a level.

You can use a simple for loop to achieve this.

Example: Spawn 10 Objects Using a For Loop

using UnityEngine;

public class MultipleSpawn : MonoBehaviour
{
    public GameObject prefab;

    void Start()
    {
        for (int i = 0; i < 10; i++)
        {
            Vector3 spawnPosition =
                new Vector3(i * 2f, 0f, 0f);

            Instantiate(
                prefab,
                spawnPosition,
                Quaternion.identity
            );
        }
    }
}

When you run this script, Unity creates ten copies of the Prefab. Each object appears at a different position along the X-axis, with a spacing of two units.

Example: Spawn Objects at Random Positions

What if you want to spawn collectibles or enemies at random locations?

You can use Unity’s Random.Range method to generate random coordinates.

using UnityEngine;

public class RandomSpawner : MonoBehaviour
{
    public GameObject prefab;

    void Start()
    {
        for (int i = 0; i < 10; i++)
        {
            float randomX = Random.Range(-5f, 5f);
            float randomZ = Random.Range(-5f, 5f);

            Vector3 randomPosition =
                new Vector3(randomX, 0f, randomZ);

            Instantiate(
                prefab,
                randomPosition,
                Quaternion.identity
            );
        }
    }
}

This example generates ten objects at random positions within the specified X and Z ranges.

You can use this technique for procedural environments, resource generation, random pickups, and many other gameplay mechanics.

How to Instantiate a GameObject as a Child of Another Object

Here’s another situation you will encounter frequently.

Suppose you’re spawning bullets, particle effects, or UI elements. You may want these objects to become children of a particular GameObject so that your Hierarchy remains organized.

Unity provides an Instantiate overload that accepts a parent Transform.

Instantiate(prefab, parentTransform);

For example:

using UnityEngine;

public class ChildSpawner : MonoBehaviour
{
    public GameObject prefab;
    public Transform parentTransform;

    void Start()
    {
        Instantiate(prefab, parentTransform);
    }
}

The newly created object will become a child of the specified Transform.

You can also specify the position, rotation, and parent together:

Instantiate(
    prefab,
    transform.position,
    transform.rotation,
    parentTransform
);

This is useful when you want to create an object at a specific world position while keeping it organized under a particular parent.

Important: When using the parent-only overload, Unity interprets the clone’s position and rotation relative to the parent. If you need to preserve world-space positioning, use the appropriate overload with the world-space option.

What Happens After a GameObject Is Instantiated?

Creating a GameObject is not the end of the process. The newly instantiated object becomes part of your running game and can execute its attached scripts, interact with physics, play animations, and respond to collisions.

1. Unity Creates a Separate Instance

The new object has its own Transform and component instances. Changing the position, health, or other runtime properties of the clone does not automatically change the original object or other clones.

2. Attached Components Are Cloned

If the original Prefab contains child GameObjects, Colliders, Rigidbody components, and scripts, these are also included in the cloned hierarchy.

3. Lifecycle Methods Are Called

For active instantiated objects, Unity invokes the relevant lifecycle methods, including Awake and OnEnable. Start runs before the first Update of an enabled script.

The exact execution order matters when you’re initializing objects during gameplay. You should not assume that Awake has already executed on every other object in the scene just because you instantiated a new one.

If you want to understand how these methods work, read our guide: Unity Awake vs Start: What’s the Difference and When to Use Each?.

You can also learn about Unity OnEnable and when it runs, especially if you plan to reuse instantiated objects through pooling.

For more information, check Unity’s official Order of Execution for Event Functions.

4. You May Need to Initialize the New Object

Imagine spawning an enemy Prefab. It may already contain an EnemyHealth script, movement controller, and Animator. But what if each enemy needs a different health value or movement speed?

You can configure these properties immediately after instantiation.

GameObject enemy = Instantiate(
    enemyPrefab,
    spawnPoint.position,
    spawnPoint.rotation
);

EnemyHealth health =
    enemy.GetComponent<EnemyHealth>();

if (health != null)
{
    health.SetHealth(150);
}

Here, we instantiate the enemy and then access its EnemyHealth component to configure its initial health.

This makes your spawning system more flexible because different instances can have different runtime properties.

Practical Example: Create a Bullet Spawning System

Let’s put everything together by creating a simple bullet spawning system.

Imagine you’re developing a shooting game. Whenever the player presses the fire button, a bullet should appear at the weapon’s firing point and travel in the correct direction.

Step 1: Create a Bullet Prefab

Create a bullet GameObject and add the components required for your shooting system. For this example, we’ll use a simple movement script.

Save the bullet as a Prefab in your Project window.

Step 2: Create the Bullet Script

Create a script called Bullet.cs.

using UnityEngine;

public class Bullet : MonoBehaviour
{
    public float speed = 15f;
    public float lifeTime = 3f;

    void Start()
    {
        Destroy(gameObject, lifeTime);
    }

    void Update()
    {
        transform.Translate(
            Vector3.forward * speed * Time.deltaTime
        );
    }
}

This script moves the bullet forward and destroys it after three seconds.

For a physics-based projectile, you may instead use Rigidbody velocity or force, depending on your movement requirements.

Step 3: Create the Shooting Script

Now create another script named PlayerShoot.cs.

using UnityEngine;

public class PlayerShoot : MonoBehaviour
{
    public GameObject bulletPrefab;
    public Transform firePoint;

    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            Shoot();
        }
    }

    void Shoot()
    {
        Instantiate(
            bulletPrefab,
            firePoint.position,
            firePoint.rotation
        );
    }
}

Attach this script to your player or weapon GameObject.

Assign the Bullet Prefab and create an empty child GameObject called FirePoint at the end of the weapon barrel.

Now press Play and click the fire button. Every time you shoot, Unity creates a new bullet at the firing position.

Note: This example uses Unity’s legacy Input Manager. If your project uses the newer Input System, you can replace the input check with an Input Action callback.

When you start adding hit detection to your project, you may also find our guide to Unity OnCollisionEnter, OnCollisionStay, and OnCollisionExit useful for understanding how objects interact through physics.

Does Instantiate Affect Game Performance?

Now that you know how to create GameObjects, let’s discuss something that becomes important as your game grows: performance.

Instantiate is extremely useful, but creating too many objects repeatedly can affect your game’s performance.

For example, imagine a bullet-hell game where hundreds of bullets are created and destroyed every second. Each new instance requires Unity to create and initialize an object and its associated components.

Repeated creation and destruction can introduce CPU overhead and garbage collection pressure, depending on the objects and systems involved. This may result in frame-time spikes or noticeable stuttering.

Here are some situations where excessive instantiation can become problematic:

  • Games with large numbers of projectiles.
  • Games spawning many enemies simultaneously.
  • Particle-heavy games with frequent effects.
  • Mobile games with limited processing resources.
  • Games that repeatedly create and destroy complex objects.

So, should you stop using Instantiate? Absolutely not.

The important thing is knowing when to use it and when another object-management technique would be more appropriate.

For a broader look at performance improvements, check out our guide: 15+ Essential Unity Game Optimization Tips: Boost Performance and FPS.

Object Pooling: A Better Alternative for Frequently Spawned Objects

One of the most common techniques for managing frequently created objects is Object Pooling.

Instead of continuously creating and destroying objects, you create a collection of objects in advance. When an object is needed, you activate an available instance. When it is no longer needed, you deactivate it and return it to the pool.

Let’s understand this with a simple bullet example.

Without Object Pooling:

  1. Player fires a bullet.
  2. Unity creates a new bullet using Instantiate.
  3. Bullet travels through the scene.
  4. Bullet gets destroyed.
  5. The same process repeats.

With Object Pooling:

  1. Create a collection of bullets in advance.
  2. When the player fires, activate an available bullet.
  3. Move the bullet and perform its gameplay logic.
  4. When the bullet is no longer needed, deactivate it.
  5. Reuse the same bullet for the next shot.

This reduces repeated creation and destruction, making it especially useful for systems that frequently reuse the same types of objects.

If you want to implement this in your own game, read our detailed tutorial: Unity Object Pooling: How to Improve Game Performance.

Simple Object Pooling Example

Here is a basic implementation using a Queue to store inactive bullets.

using UnityEngine;
using System.Collections.Generic;

public class BulletPool : MonoBehaviour
{
    public GameObject bulletPrefab;
    public int poolSize = 20;

    private Queue<GameObject> bulletPool =
        new Queue<GameObject>();

    void Start()
    {
        for (int i = 0; i < poolSize; i++)
        {
            GameObject bullet = Instantiate(
                bulletPrefab,
                transform
            );

            bullet.SetActive(false);
            bulletPool.Enqueue(bullet);
        }
    }

    public GameObject GetBullet(
        Vector3 position,
        Quaternion rotation
    )
    {
        if (bulletPool.Count == 0)
            return null;

        GameObject bullet = bulletPool.Dequeue();

        bullet.transform.SetPositionAndRotation(
            position,
            rotation
        );

        bullet.SetActive(true);

        return bullet;
    }

    public void ReturnBullet(GameObject bullet)
    {
        bullet.SetActive(false);
        bulletPool.Enqueue(bullet);
    }
}

This is a simple fixed-size pool. It returns null when no bullet is available rather than creating additional instances.

For a production game, you should also handle duplicate returns, reset bullet state, and decide what to do when the pool becomes empty.

Unity also provides a built-in pooling API through UnityEngine.Pool.ObjectPool<T>, which is worth exploring for more advanced projects.

If you are using pooling, remember that activating an object can invoke OnEnable again. This makes it important to understand how to reset an object’s state before reuse.

How to Destroy Instantiated GameObjects in Unity

Creating objects is important, but managing their lifetime is equally important.

If you continuously instantiate objects without removing or reusing them, your scene can become filled with unnecessary GameObjects.

Unity provides the Destroy() method to remove objects during runtime.

Destroy an Object After a Specific Time

Destroy(gameObject, 5f);

This destroys the current GameObject after five seconds.

This technique is useful for temporary objects such as bullets, explosions, and damage effects.

Destroy an Object When a Condition Is Met

void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Enemy"))
    {
        Destroy(gameObject);
    }
}

In this example, the current GameObject is destroyed when it collides with an object tagged Enemy, provided the required Collider and trigger setup is configured.

Remember that Destroy schedules the object for removal rather than immediately removing it at the exact point where the method is called.

If you’re using Object Pooling, you should generally deactivate and return the object instead of destroying it.

Common Mistakes When Using Instantiate in Unity

Although Instantiate is straightforward, beginners often encounter problems when implementing it in real projects.

1. Forgetting to Assign the Prefab

One of the most common issues is leaving the Prefab reference empty in the Inspector.

If your script tries to instantiate an unassigned reference, Unity will throw an exception.

Solution: Always assign the Prefab before running the game. You can also add a null check:

if (prefab != null)
{
    Instantiate(prefab);
}

2. Spawning Objects at the Wrong Position

Sometimes objects appear at unexpected locations because developers assume that Instantiate automatically uses the spawner’s position.

It doesn’t. When using the position and rotation overload, Unity uses the values you explicitly provide.

Solution: Use a dedicated spawn point or pass the correct Transform values.

3. Forgetting to Set the Parent

When you instantiate objects without specifying a parent, the new object does not automatically become a child of the original object.

This can make your Hierarchy difficult to manage, especially when creating large numbers of objects.

Solution: Specify a parent Transform when appropriate.

4. Creating Too Many Objects

Repeatedly instantiating objects without considering their lifetime can increase memory usage and create performance problems.

Solution: Destroy temporary objects when they are no longer needed, or implement Object Pooling for frequently reused objects.

5. Forgetting to Initialize New Instances

Just because a Prefab has all its components doesn’t mean every instance automatically receives the gameplay data it needs.

For example, enemies may require different health values, movement speeds, or target references.

Solution: Initialize the newly created instance after calling Instantiate.

6. Confusing the Original Object with Its Clone

Instantiate creates a new copy. It doesn’t move the original object to another location.

Changes made to the clone should be performed using the returned reference.

GameObject clone = Instantiate(
    prefab,
    transform.position,
    Quaternion.identity
);

clone.name = "NewEnemy";

Best Practices for Building a Reliable Spawning System

As your Unity project becomes larger, you may have multiple systems responsible for spawning enemies, bullets, collectibles, and effects.

Keeping these systems organized from the beginning can save you a lot of debugging time later.

  • Use Prefabs: Keep reusable GameObjects in Prefabs instead of relying heavily on objects placed directly in the scene.
  • Centralize spawning logic: Create reusable spawning methods instead of scattering Instantiate calls throughout your project.
  • Use dedicated spawn points: Define clear locations for enemies, bullets, and other objects.
  • Initialize instances: Set health, speed, targets, and other required properties after creation.
  • Use Object Pooling: Consider pooling for objects that are created and destroyed frequently.
  • Manage object lifetimes: Decide when objects should be destroyed, disabled, or returned to a pool.
  • Test heavy gameplay scenarios: Test situations involving many enemies, consecutive shots, and frequent effects.
  • Organize your Hierarchy: Assign suitable parents to spawned objects where appropriate.

When working with explosions, sparks, and other short-lived visual effects, our guide to Unity Particle System: A Complete Guide to Creating Effects can help you explore another practical use case for runtime object creation.

A well-designed spawning system should be easy to maintain, reusable across different gameplay systems, and capable of handling heavy gameplay situations.

Frequently Asked Questions About Unity Instantiate

1. What does Instantiate do in Unity?

Instantiate creates a copy of an existing GameObject or Unity object during runtime. It is commonly used to spawn enemies, bullets, collectibles, particle effects, and other gameplay objects.

2. Can I use Instantiate without a Prefab?

Yes. You can instantiate an existing GameObject from the scene or another supported Unity object. However, using Prefabs is generally more reliable for reusable runtime spawning because they provide a reusable asset reference.

3. What is the difference between Instantiate and Destroy in Unity?

Instantiate creates a new copy of an object, whereas Destroy removes an existing object from the scene. They are commonly used together to manage the lifetime of runtime-created GameObjects.

4. How do I instantiate a GameObject at a specific position?

Use the position and rotation overload:

Instantiate(
    prefab,
    new Vector3(0, 2, 0),
    Quaternion.identity
);

This creates the object at the specified world position with no additional rotation.

5. Does Instantiate copy all components of a GameObject?

Yes. When you instantiate a GameObject, Unity also clones its attached components and child GameObjects, including their associated components and properties.

6. Does Instantiate affect performance?

Instantiate has a processing cost because Unity needs to create and initialize a new object and its components. Occasional calls are generally fine, but repeatedly creating large numbers of objects can cause performance issues. Object Pooling is a common solution.

7. How can I instantiate multiple objects in Unity?

You can use a for loop and call Instantiate inside it. This allows you to create multiple copies of the same Prefab at different positions.

8. What is the difference between Instantiate and Object Pooling?

Instantiate creates a new object when needed, while Object Pooling reuses previously created objects. Pooling is particularly useful when the same objects are created and destroyed frequently, such as bullets and enemies.

9. Does Instantiate call Awake and Start?

For active instantiated GameObjects, Unity calls Awake and OnEnable as part of their initialization. Start runs before the first Update on an enabled script. Inactive objects have different lifecycle timing, so you should account for their active state when designing initialization logic.

10. How do I access a component of an instantiated GameObject?

Store the returned GameObject reference and use GetComponent:

GameObject enemy = Instantiate(
    enemyPrefab,
    spawnPoint.position,
    spawnPoint.rotation
);

EnemyHealth health =
    enemy.GetComponent<EnemyHealth>();

You can then access the component and configure its properties.

Final Thoughts

Unity Instantiate is one of those methods that every Unity developer should understand. From creating simple bullets to building complex enemy spawning systems and procedural environments, it gives you the flexibility to create objects exactly when your game needs them.

Start with simple Prefab spawning, learn how to control position and rotation, and gradually build more advanced systems with initialization, object cleanup, and pooling.

One final recommendation: don’t focus only on learning how to create GameObjects. Learn how to manage their entire lifecycle. Knowing when to instantiate, initialize, reuse, and destroy objects will help you build cleaner and more efficient Unity games.

Did this tutorial help you understand Unity Instantiate? If it did, consider sharing it with other Unity developers who might find it useful. If you have a question, a different approach, or an interesting spawning technique, leave a comment below. I’d love to hear how you’re using Instantiate in your projects!

Happy game development!


Additional Resources

Leave a Reply

Your email address will not be published. Required fields are marked *