如何暂停for循环,直到按Enter键?

时间:2019-11-15 12:43:10

标签: c# unity3d

例如

bool x = false;

if(press enter)
{
  x = true;
}
for(int i = 0; i < 10; i++)
{
  if(x == true)
    print (i);

  x = false;
}

这样的代码在按Enter键后总是给我0,而不是整个序列1,2,3 ... 10。

我在网上找到了三个答案,但是它们都不是用c#编写的,实际上我是在Unity中使用它的,所以它必须是c#。

3 个答案:

答案 0 :(得分:2)

for(int i = 0; i < 10; i++)
{
    if(x == true)
        print(i);

    // This line is executed allways
    x = false;
}

那是怎么回事

  • 在第一个呼叫x == true中,因此它打印0
  • 然后它设置x = false
  • 在以后的迭代x == false =>中,因此不再有输出。

您可能想要类似的东西

// only check this once since it isn't changed in the loop
// do not loop at all if button wasn't pressed
if(x)
{
    // Do all prints in a loop
    for(int i = 0; i < 10; i++)
    {
        print(i);    // prints 0 1 2 3 4 5 6 7 8 9
    }

    // reset the flag so you do the printing only in the frame
    // where the button was pressed
    x = false;
}

对于特定于Unity的用户,您可能希望使用Input.GetKeyDown而不是x

答案 1 :(得分:0)

您可以在释放返回键的帧中运行for循环。这样可以确保我们不会在关键帧按下的每个帧中都运行此命令(我假设您不希望这样做)。为此,我们只需要检查Input.GetKeyUp,该键在释放指定的键时将返回一个布尔值。

if(Input.GetKeyUp(KeyCode.Return))
{
    for(int i = 0; i < 10; i++)
        print(i);
}

答案 2 :(得分:0)

您可以将Coroutine与Input.GetKeyDown结合使用,然后返回收益。

例如:

private bool _pause = false;

private void Start()
{
  StartCoroutine(FuncName());
}

private void Update()
{
  if (Input.GetKeyDown(KeyCode.Return))
  {
    _pause = !_pause;
  }
}

private IEnumerator FuncName()
{
  for(int i = 0; i < 10; i++)
  {
    while (_pause)
    {
      yield return null;
      print (i);
    }
  }
}
相关问题