Repeat a line of code after pressing a key

Viewed 232

Pretty simple. Is there any way to repeat this code, with the press of a key, indefinitely until i press another key?

The Code:

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

Space, in this case, would be the button to start the repeating code. GridScan is a function that needs variables so it won't work with Invokerepeat (I don't think, tell me otherwise if im wrong).

1 Answers

You can handle that with a boolean to execute that in the update. For example:

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);
    }
}

That is not tried pseudocode just to give you the idea. Coroutines are also a good option when you have a specific condition to wait for.

EDIT: Find code with coroutine:

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);
        }
    }
} 

You can attach the script to a gameObject in your scene to see how it works. Change the Debug.LogError("Running"); with your grid.GridScan(new Vector3(0, 0, 0), 100); to then use it in your code.

Related