门
本课属于 Coddy Unity 学习旅程的“物理与游戏玩法”单元。第 71 课,共 71 课。
这个挑战将完成本单元的学习:把盘子设为触发器,将代码放在一个脚本中,并用协程控制门,等待门口清空后再运行。
挑战
困难当出现 Unlocked 时打开门,稍后再关上,但不要在玩家还在门边时关门。
- 编写
IEnumerator OpenDoor():执行door.SetActive(false);,然后执行yield return new WaitForSeconds(openTime);。 - 接着执行
while (Physics.CheckSphere(doorway.position, 1f, LayerMask.GetMask("Player"))),并在循环中执行yield return null;。 - 最后执行
door.SetActive(true);,并记录Door closed。记录Unlocked后,用StartCoroutine(OpenDoor());启动它。
点击 “开始”,解锁门并离开。然后点击 “检查”。
亲手试试
using System.Collections;
using UnityEngine;
public class CodeLock : MonoBehaviour
{
[SerializeField] private Renderer[] plates;
[SerializeField] private GameObject door;
[SerializeField] private Transform doorway;
[SerializeField] private float openTime = 4f;
private int next = 1;
public void Press(int number)
{
if (number == next)
{
Debug.Log("Plate " + number);
next++;
if (next > 3)
{
Debug.Log("Unlocked");
next = 1;
}
}
else
{
Debug.Log("Wrong plate");
next = 1;
StartCoroutine(Flash());
}
}
IEnumerator Flash()
{
foreach (Renderer plate in plates)
{
plate.material.color = Color.red;
}
yield return new WaitForSeconds(1f);
foreach (Renderer plate in plates)
{
plate.material.color = Color.gray;
}
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
物理与游戏玩法中的所有课
自己练习: Unity 在线编辑器