创建for循环等待用户输入



我在VR中编程一个任务,用户听到一个带有一定数量的数字的音频文件,然后需要按下一个键。如果他做对了,那么他应该按下"&;&;"然后播放一个长一个数字的音频文件。如果他做错了,他应该按"为什么"。如果这是他在正确答案后的第一个错误答案,将播放一个音频文件,其中包含与之前相同数量的数字。如果他做错了,并且在此之前已经做错了,那么数字的数量将减少1。

总共有10个音频文件,这就是为什么我决定使用for循环。

但是现在我不知道如何让for循环等待用户输入。我也读到,当你必须等待用户输入时,通常不适合使用for循环,但我不知道我还能做什么。

下面是我的代码:
IEnumerator playDSBtask()
{
bool secondWrong = false;
fillList();
for (int i = 0; i < 10; i = i + 1)
{
List<AudioSource> x = chooseList(score);
AudioSource myAudio = x[0];
float duration = myAudio.clip.length;
myAudio.GetComponent<AudioSource>();
myAudio.Play();
yield return new WaitForSeconds(duration + 5);
if (Input.GetKeyDown("r"))
{
score++;
secondWrong = false;
}
else if (Input.GetKeyDown("f") && secondWrong == false)
{
secondWrong = true;
}
else if (Input.GetKeyDown("f") && secondWrong == true)
{
score--;
}

x.Remove(myAudio);
}
}

但是这不起作用,因为如果if或else if语句都不为真,则for循环将继续执行。

在你的例子中使用for循环是完全可以的,因为它是在协程中,你在它内部屈服,所以不会有无限循环,因此主线程冻结。

你可以使用WaitUntil,比如

...
yield return new WaitForSeconds(duration + 5);
// Wait until any o the expected inputs is pressed
yield return WaitUntil(() => Input.GetKeyDown("r") || Input.GetKeyDown("f"));
// then check which one exactly
if (Input.GetKeyDown("r"))
{
...

或者,这也可以用更通用的方式完成,但也更容易出错

...
yield return new WaitForSeconds(duration + 5);
// wait until something breaks out of the loop
while(true)
{
// check if any key was pressed
if(Input.anyKeyDown)
{
// handle r key
if (Input.GetKeyDown("r"))
{
score++;
secondWrong = false;
// important!
break;
}
else if (Input.GetKeyDown("f"))
{
if(!secondWrong)
{
secondWrong = true;
}
else
{
score--;
}
// Important!
break;
}
}
// if nothing called break wait a frame and check again
yield return null;
}
x.Remove(myAudio);
...

一般情况下,您可能希望使用KeyCode.FKeyCode.R来代替字符串。


从用户体验的角度来看,你要么想要减少5秒的等待,要么/并在用户输入被处理/等待时显示某种UI反馈。

最新更新