按键后重复一行代码
Repeat a line of code after pressing a key
很简单。有什么方法可以通过按一个键无限期地重复此代码,直到我按另一个键为止?
代码:
if (Input.GetKeyDown(KeyCode.Space))
{
grid.GridScan(new Vector3(0, 0, 0), 100);
}
Space,在这种情况下,将是开始重复代码的按钮。 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, 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);
}
}
}
您可以将脚本附加到场景中的游戏对象以查看其工作原理。
用您的 grid.GridScan(new Vector3(0, 0, 0), 100);
更改 Debug.LogError("Running");
,然后在您的代码中使用它。
很简单。有什么方法可以通过按一个键无限期地重复此代码,直到我按另一个键为止?
代码:
if (Input.GetKeyDown(KeyCode.Space))
{
grid.GridScan(new Vector3(0, 0, 0), 100);
}
Space,在这种情况下,将是开始重复代码的按钮。 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, 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);
}
}
}
您可以将脚本附加到场景中的游戏对象以查看其工作原理。
用您的 grid.GridScan(new Vector3(0, 0, 0), 100);
更改 Debug.LogError("Running");
,然后在您的代码中使用它。