Menu
CoddyTech

Spawn on a Timer

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 63 of 85.

A spawner that makes something every few seconds needs a timer. Time.deltaTime is the time the last frame took, so adding it up in a field on every Update() gives the seconds that have passed. When the total reaches the interval, spawn, and take the interval off the total.

This fountain throws a water drop every half second:

public GameObject dropPrefab;
public float interval = 0.5f;
float timer;

void Update()
{
    timer += Time.deltaTime;
    if (timer >= interval)
    {
        Instantiate(dropPrefab, transform.position, Quaternion.identity);
        timer -= interval;
    }
}

timer -= interval keeps the leftover: if the frame ended at 0.51 seconds, the next half second starts counting from 0.01, and the drops stay on the beat. timer = 0 would throw that leftover away, so each drop would come a little late and the delay would add up over a long game. timer is private because nobody needs to set it in the Inspector.

challenge icon

Challenge

Medium

Drop a box every interval seconds (2 in the Inspector).

  1. Add float timer; and int count; fields. In Update(), add Time.deltaTime to timer.
  2. When timer >= interval, call Instantiate(boxPrefab, transform.position, Quaternion.identity); and take interval off timer.
  3. Then add 1 to count and log "Box " + count.

Press Play: a box drops every 2 seconds, and the Console counts Box 1, Box 2. Then Check.

Try it yourself

using UnityEngine;

public class BoxDropper : MonoBehaviour
{
    public GameObject boxPrefab;
    public float interval = 1f;

    void Update()
    {
        // Every interval seconds: drop a box and log "Box 1", "Box 2"...
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground