Unity Input System Dectects Multiple button presses

I am creating my own little adventure game and I was trying to develop a way to sprint before I start designing the level.
I used this code for sprinting and not sprinting

if (Input.GetKeyDown (KeyCode.Z)){
			speed = speed + 5;
			Debug.Log ("Z was pressed");
				//"Sprinting"
			}
		if (Input.GetKeyUp (KeyCode.Z)) {
			speed = speed -5;
			Debug.Log ("Z was released");
		}

When I hold down the button it does a burst of 3 so it makes my speed increase by 15 but when I released the button it only subtracts it only decreases my speed by 5. And isn’t always in bursts of threes making it unpredictable. Which makes my speed end up with values of 25, 40, 35 and a lot of multiples of five. Hitting the button again doesn’t fix anything and only makes it worse. Does anyone know any code that would help fix this problem?

Depending on what function you have that in it’s possible that it can be called multiple times a frame. One solutions is to have a flag in your class like bool isRunning to store whether or not the player is running. And in the movement portion of your class you simply make your calculation with the additional movement speed.

You could also use that same flag and simply modify your current code to check if (Input.GetKeyDown (KeyCode.Z) && !isRunning) and if (Input.GetKeyUp (KeyCode.Z) && isRunning) to prevent multiple catches.

Ultimately it’s not usually a good idea to modify the speed value directly since it should usually just be used as a base value for movement speed. Then during your movement calculation you take into account whether or not there should be any additional values added to the movement calculation (like running or being slowed down for some reason).