Menu
CoddyTech

Spawn on a Timer

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 49 of 67.

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

The Dropper should drop a box every interval seconds (the Inspector says 2): the first box 2 seconds after Play, then one more every 2 seconds.

  • Spawn each box at the dropper's position, with no rotation.
  • After each box, log its number: Box 1, Box 2 and so on.

Press Play and watch the pile grow, 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"...
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics