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
MediumThe 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 2and 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"...
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon6GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch9Prefabs and Spawning
Prefabs and InstantiateSpawn on a TimerSpawn in a GridLists of ObjectsDestroyRandom SpawnsRecap: Fireworks