Your First Coroutine
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 23 of 63.
Update() must finish every frame, so it cannot wait. A coroutine can: it is a method that pauses and carries on later, right where it stopped. It returns IEnumerator, which needs using System.Collections;, and each yield return in it is a pause. In C#, yield return makes a method that hands out its values one at a time; Unity asks for the next one when the wait is over. yield return null waits one frame, and yield return new WaitForSeconds(3f) waits 3 seconds.
StartCoroutine(Cycle()) starts one. This traffic light goes green, yellow 3 seconds later, and red after one more second:
using System.Collections;
using UnityEngine;
public class TrafficLight : MonoBehaviour
{
Renderer lamp;
void Start()
{
lamp = GetComponent<Renderer>();
StartCoroutine(Cycle());
}
IEnumerator Cycle()
{
lamp.material.color = Color.green;
yield return new WaitForSeconds(3f);
lamp.material.color = Color.yellow;
yield return new WaitForSeconds(1f);
lamp.material.color = Color.red;
}
}StartCoroutine runs the coroutine up to its first yield at once, then Start() carries on; Unity resumes it after each wait, with its local variables as they were. A bare Cycle(); without StartCoroutine does nothing: it builds the paused method and drops it, and not one line of it runs. And yield return 3f; is not a 3 second wait: Unity only knows wait objects such as WaitForSeconds and treats any other value as one frame.
Challenge
EasyThe Spikes wait under the floor. Make Space spring the trap with a coroutine named Spring:
- At once: log
Click. - Half a second later: the spikes jump up 1 unit.
- 2 seconds after that: they sink back down 1 unit.
Press Play, press Space and watch, then Check.
Try it yourself
using System.Collections;
using UnityEngine;
public class SpikeTrap : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
// Spring the trap with a coroutine
}
}
// IEnumerator Spring(): Click, wait 0.5 s, up 1 unit, wait 2 s, down 1 unit
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall