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
MediumDrop a box every interval seconds (2 in the Inspector).
- Add
float timer;andint count;fields. InUpdate(), addTime.deltaTimetotimer. - When
timer >= interval, callInstantiate(boxPrefab, transform.position, Quaternion.identity);and takeintervalofftimer. - Then add 1 to
countand 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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch11Prefabs and Spawning
Prefabs and InstantiateSpawn on a TimerSpawn in a GridLists of ObjectsTake Back the NewestDestroyRandom SpawnsRecap: Fireworks6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground