你的第一个协程
本课属于 Coddy Unity 学习旅程的“物理与游戏玩法”单元。第 24 课,共 71 课。
Update() 必须在每一帧内完成,因此不能等待。协程可以:它是一种可以暂停并在之后从停止处继续执行的方法。它返回 IEnumerator,因此需要 using System.Collections;,其中的每个 yield return 都会暂停执行。在 C# 中,yield return 会让方法一次交出一个值;等待结束后,Unity 会请求下一个值。yield return null 会等待一帧,yield return new WaitForSeconds(3f) 会等待 3 秒。
StartCoroutine(Cycle()) 会启动一个协程。这个交通灯先变绿,3 秒后变黄,再过 1 秒后变红:
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 会立即运行协程,直到遇到第一个 yield,然后 Start() 继续执行;每次等待结束后,Unity 都会恢复协程,并保留其局部变量的原有值。不使用 StartCoroutine 的直接调用 Cycle(); 不会产生任何效果:它会创建这个暂停的方法,然后将其丢弃,方法中的代码一行也不会运行。并且,yield return 3f; 并不代表等待 3 秒:Unity 只识别 WaitForSeconds 之类的等待对象,其他任何值都会被视为等待一帧。
挑战
简单用协程让尖刺陷阱在按下空格键时弹起。
- 编写
IEnumerator Spring():记录Click,然后执行yield return new WaitForSeconds(0.5f);,接着执行transform.position += Vector3.up;。 - 然后用同样的方法等待 2 秒,再减去
Vector3.up。 - 在空格键对应的
if中,用StartCoroutine(Spring());启动它。
按下“开始”,再按空格键:尖刺会跳起,然后沉下去。接着点击“检查”。
亲手试试
using System.Collections;
using UnityEngine;
public class SpikeTrap : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
// 用协程触发陷阱
}
}
// IEnumerator Spring():点击,等待 0.5 s,上升 1 个单位,等待 2 s,下降 1 个单位
}
物理与游戏玩法中的所有课
自己练习: Unity 在线编辑器