Your First Coroutine
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 24 of 71.
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
EasyMake Space spring the spike trap with a coroutine.
- Write
IEnumerator Spring(): logClick,yield return new WaitForSeconds(0.5f);, thentransform.position += Vector3.up;. - Then wait 2 seconds the same way and take
Vector3.upaway again. - In the Space
if, start it withStartCoroutine(Spring());.
Press Play and press Space: the spikes jump up, then sink. 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
}
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: Countdown10Project: Arena Escape
The ArenaHunters2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable WallPractice on your own: Unity playground