Trying to repeat only 1 time an action in the Update() for distances on button press

Hello, my probleme is that i have a script called Distance manager which must display the distance done by the player, but my goal is to add +1 to a variable called “distance” when i press “Z”. The probleme is that when i press “Z”, instead of adding only 1 per second, the distance add +1, 60 times a second so i would like to fix this as soon as possible. Ty to the people who will help me :smiley:
Here is my script.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DistanceMangerV2 : MonoBehaviour
{

    public Text distanceMoved;
    public Text marketDistance;
    public float distance;
    [HideInInspector] public int boughtDistance;


    void Update()
    {
        if (Input.GetKey(KeyCode.Z))
        {
            StartCoroutine("DistanceCounter");
        }

        distanceMoved.text = (distance + boughtDistance).ToString();
        marketDistance.text = (distance + boughtDistance).ToString();
    }

    IEnumerator DistanceCounter()
    {
        distance++;
        yield return new WaitForSeconds(1f);
    }
}

Your code will start a new “DistanceCounter” coroutine every frame while you have the Z key pressed.

A quick solution could be limit the execution with a boolean value like this:

using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 
 public class DistanceMangerV2 : MonoBehaviour
 {
 
     public Text distanceMoved;
     public Text marketDistance;
     public float distance;
     [HideInInspector] public int boughtDistance;
     private bool isExecuting = false;

 
 
     void Update()
     {
         if (Input.GetKey(KeyCode.Z) && !isExecuting)
         {
             isExecuting = true;
             StartCoroutine("DistanceCounter");
         }
 
         distanceMoved.text = (distance + boughtDistance).ToString();
         marketDistance.text = (distance + boughtDistance).ToString();
     }
 
     IEnumerator DistanceCounter()
     {
         distance++;
         yield return new WaitForSeconds(1f);
         isExecuting = false;
     }
 }

When you’ll press Z, the isRunning will be set to true so the Coroutine won’t be executed again while isRunning = true. Then, setting isRunning to false when the coroutine finishes, will enable the execution again.

Not the solution I like most, but should work.

Best regards!
Rodri