Unity c#协程不工作
本文关键字:工作 程不 Unity | 更新日期: 2023-09-27 18:04:25
我正在尝试制作一个Simon游戏。显然,当显示一种颜色时,它应该等待一秒钟左右。当游戏告诉你该怎么做时,我创建了一个规则。在协程中,它应该首先暂停,当我运行游戏时,它确实暂停了。然后它会选择颜色之类的东西。然后它应该回圈(我做了一个循环)并再次暂停,并再次执行所有操作。问题是,暂停只在第一次有效。然后它会显示其他颜色大约半秒,然后结束。我不明白为什么一旦它循环,它似乎做了一切,除了暂停。下面是我的代码:
void Update () {
if (show == true) {
StartCoroutine(Show());
}
}
IEnumerator Show() {
do {
yield return new WaitForSeconds(2f);
round ++;
if (round == 1) {
on = Random.Range(1,5);
}
if (round == 2) {
on = Random.Range(1,5);
}
if (round == 3) {
on = Random.Range(1,5);
}
if (round == 4) {
on = Random.Range(1,5);
}
// Turn on/off lights
if (on == 1) {
green.GetComponent<Renderer>().material = greenMat;
}
if (on != 1) {
green.GetComponent<Renderer>().material = greenOff;
}
if (on == 2) {
red.GetComponent<Renderer>().material = redMat;
}
if (on != 2) {
red.GetComponent<Renderer>().material = redOff;
}
if (on == 3) {
yellow.GetComponent<Renderer>().material = yellowMat;
}
if (on != 3) {
yellow.GetComponent<Renderer>().material = yellowOff;
}
if (on == 4) {
blue.GetComponent<Renderer>().material = blueMat;
}
if (on != 4) {
blue.GetComponent<Renderer>().material = blueOff;
}
}while(show == true);
}
我写了一个协程,可能会对你有所帮助。把它放在开始档
IEnumerator Show()
{
while (true) // or show
{
yield return new WaitForSeconds(2f);
round ++;
if (round >= 1 && round <= 4)
on = Random.Range(1,5);
green.GetComponent<Renderer>().material = on == 1 ? greenMat : greenOff;
//Same for the other...
}
}