Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 36 ยท C# Scripting

Instantiate, Destroy and Coroutines

Create and remove objects at run time with Instantiate and Destroy, wait and sequence actions with coroutines and yield, and see how coroutines work with runnable C# iterators.

Games constantly create and remove things: bullets leave a gun, enemies spawn in waves, pickups vanish after a few seconds. And they constantly wait: a door opens after a delay, a boss shouts three times, an explosion fades out. This lesson covers the two functions for creating and removing objects, Instantiate and Destroy, and the coroutine, Unity's tool for code that runs over several frames.

Unity scripts are read-only in this lesson. The coroutine mechanism is plain C# (it is built from iterators), so the runnable stand-ins show exactly how it works.

Instantiate

Instantiate makes a copy of a prefab (or any GameObject or component) at run time:

C#
using UnityEngine;

public class Gun : MonoBehaviour
{
    [SerializeField] GameObject bulletPrefab;
    [SerializeField] Transform muzzle;
    [SerializeField] float bulletSpeed = 20f;

    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            GameObject bullet = Instantiate(bulletPrefab, muzzle.position, muzzle.rotation);
            bullet.GetComponent<Rigidbody>().linearVelocity = muzzle.forward * bulletSpeed;
        }
    }
}

Overloads:

  • Instantiate(prefab): at the prefab's own position, no parent.
  • Instantiate(prefab, position, rotation): placed and rotated.
  • Instantiate(prefab, parent): becomes a child of parent.
  • Instantiate(prefab, position, rotation, parent): all of the above.

If you declare the field as a component type (public Bullet bulletPrefab;), Instantiate returns that component directly, saving a GetComponent call. The returned object is the clone; the prefab asset itself is never modified.

Destroy

Destroy removes an object or component at the end of the current frame:

C#
Destroy(gameObject);              // the whole object (and its children)
Destroy(gameObject, 3f);          // after 3 seconds
Destroy(GetComponent<Rigidbody>()); // only that component

The delayed form is perfect for bullets and effects: Destroy(gameObject, 5f) in the bullet's Start removes it if it never hit anything. After Destroy, the object stays alive until the frame ends, so code in the same method still runs. Do not touch the object in later frames, since Unity treats it as null.

DestroyImmediate exists but is meant only for editor scripts. In a game it can corrupt the frame's work.

Object pooling

Creating and destroying many objects (hundreds of bullets per second) makes the garbage collector work and can cause frame drops. Pooling reuses objects instead: deactivate instead of destroy, and reactivate instead of instantiate. Unity provides UnityEngine.Pool.ObjectPool<T> for this; the idea is shown below in plain C#.

C# A tiny object pool (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Six shots, but only one bullet object was ever created. In a real game you would do the same with prefab instances: SetActive(false) to release, SetActive(true) plus a reposition to reuse.

Coroutines: code that spans frames

A coroutine is a method that can pause and resume. It returns IEnumerator, uses yield return to say how long to wait, and is started with StartCoroutine:

C#
using System.Collections;
using UnityEngine;

public class Door : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(OpenAfterDelay());
    }

    IEnumerator OpenAfterDelay()
    {
        Debug.Log("Waiting...");
        yield return new WaitForSeconds(2f);     // pause for 2 seconds
        Debug.Log("Opening!");
        transform.Translate(Vector3.up * 3f);
    }
}

When Unity reaches a yield return, it saves the method's state and returns control to the game. Later, when the wait is over, it resumes right after the yield. Nothing runs on another thread: a coroutine is still on the main thread, just sliced into pieces.

What you can yield

Statement Resumes
yield return null; next frame
yield return new WaitForSeconds(2f); after 2 seconds of scaled time
yield return new WaitForSecondsRealtime(2f); after 2 seconds, ignoring timeScale
yield return new WaitForFixedUpdate(); next physics step
yield return new WaitForEndOfFrame(); after rendering this frame
yield return new WaitUntil(() => ready); when the condition becomes true
yield return new WaitWhile(() => busy); when the condition becomes false
yield return StartCoroutine(Other()); when another coroutine finishes
yield break; ends the coroutine early

Sequences and loops

Coroutines make step-by-step logic easy to read. A spawner that creates waves:

C#
IEnumerator SpawnWaves()
{
    for (int wave = 1; wave <= 3; wave++)
    {
        for (int i = 0; i < wave * 2; i++)
        {
            Instantiate(enemyPrefab, RandomSpawnPoint(), Quaternion.identity);
            yield return new WaitForSeconds(0.5f);
        }
        yield return new WaitForSeconds(3f);     // rest between waves
    }
}

And a smooth fade over time, something Update would need extra state for:

C#
IEnumerator FadeOut(CanvasGroup group, float duration)
{
    float t = 0f;
    while (t < duration)
    {
        t += Time.deltaTime;
        group.alpha = 1f - t / duration;
        yield return null;                       // wait one frame
    }
    group.alpha = 0f;
}

Starting and stopping

C#
Coroutine routine = StartCoroutine(SpawnWaves());
StopCoroutine(routine);        // stop one
StopAllCoroutines();           // stop every coroutine on this script

Coroutines stop automatically when the GameObject is destroyed or deactivated, but not when only the script is disabled. Storing the Coroutine handle lets you avoid starting the same routine twice.

How a coroutine works: a plain C# simulation

The C# compiler turns a method with yield return into an iterator: an object you advance with MoveNext(). Unity's scheduler is nothing but a loop that calls MoveNext() at the right time. This stand-in builds a tiny scheduler: each frame it checks which routines are ready.

C# A mini coroutine scheduler (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two routines run "at the same time" on one thread: Blink wakes every half second while OpenAfterDelay sleeps for two seconds. This is the real structure of Unity's coroutines, minus the engine details.

Using a coroutine for a countdown

The classic example, written like game code with a stand-in clock: it prints a countdown and then "GO!".

C# Countdown with yield (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Pitfalls

  • Starting a coroutine on an inactive object throws an error.
  • new WaitForSeconds allocates memory each time; cache it in a field (static readonly WaitForSeconds half = new(0.5f);) when used in loops.
  • A coroutine cannot return a value; use a callback or a field.
  • Exceptions inside a coroutine stop only that coroutine and are logged in the Console.
  • Modern Unity also supports async/await through Awaitable, which allows returning values; coroutines remain the most common and simplest tool.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does Destroy(gameObject) actually remove the object?

    Destroy is deferred to the end of the frame, so the rest of your method still runs.
  2. 2. What does yield return new WaitForSeconds(2f) do in a coroutine?

    Only that coroutine waits; Update and other coroutines keep running.
  3. 3. Why use an object pool for bullets?

    Reusing objects avoids repeated allocation and garbage collection.
  4. 4. Which keeps a coroutine running when you only disable the script component?

    A coroutine belongs to the GameObject's activity, not the script's enabled flag.

Summary

  • Instantiate clones a prefab (optionally with position, rotation and parent); Destroy removes at the end of the frame, optionally after a delay.
  • Pool frequently created objects.
  • A coroutine is an IEnumerator started with StartCoroutine; yield return pauses it and Unity resumes it later on the main thread.
  • Use WaitForSeconds, null, WaitUntil and friends to wait; cache the wait objects.
  • Coroutines die with their GameObject; stop them with StopCoroutine or StopAllCoroutines.

Next: Rigidbody and Colliders