按下键后重复一行代码

问题描述

非常简单。有什么方法可以无限期地重复此代码,只要按下一个键?

代码

if (Input.GetKeyDown(KeyCode.Space))
{
    grid.GridScan(new Vector3(0,0),100);
}

在这种情况下,空格将是开始重复代码的按钮。 GridScan是一个需要变量的函数,因此它不能与Invokerepeat一起使用(我不认为,如果我做错了,请告诉我,否则)。

解决方法

您可以使用布尔值来处理它,以在更新中执行它。例如:

private bool _executeOnUpdate = false;

void Update()
{
    if (Input.anyKey)
    {
        if (!_executeOnUpdate) {
            if (Input.GetKeyDown(KeyCode.Space)) 
                _executeOnUpdate = true;
        } else {
            _executeOnUpdate = false;
        }
    }
    if (_executeOnUpdate){
        grid.GridScan(new Vector3(0,0),100);
    }
}

那不是为了给您一个想法而尝试过的伪代码。 当您有特定条件要等待时,协程也是一个不错的选择。

编辑:使用协程查找代码:

using System.Collections;
using UnityEngine;

public class ExecuteUntilKeyPressed : MonoBehaviour {
    private IEnumerator myCoroutine;
    private bool _coroutineRunning = false;
    private void Start() {
        myCoroutine = runEveryHalfSec(0.5f);
    }

    void Update() {
        if (Input.anyKeyDown) {
            if (Input.GetKeyDown(KeyCode.Space)) {
                if (!_coroutineRunning) {
                    _coroutineRunning = true;
                    StartCoroutine(myCoroutine);
                }
                else {
                    StopCoroutine(myCoroutine);
                    _coroutineRunning = false;
                }
            } else {
                StopCoroutine(myCoroutine);
                _coroutineRunning = false;
            }
        }  
    }

    private IEnumerator runEveryHalfSec(float seconds) {
        while (true) {
            Debug.LogError("Running");
            yield return new WaitForSeconds(seconds);
        }
    }
} 

您可以将脚本附加到场景中的gameObject上,以查看其工作原理。 将Debug.LogError("Running");更改为grid.GridScan(new Vector3(0,100);,然后在代码中使用它。