I’m trying to get my player’s fuel to drain at a constant rate when the up arrow is held and then return to the normal fuel drain rate when the up arrow is released. So the fuel is draining at X rate when the up arrow is not held and 2X when it is held.
I’m very new to programming and threw this together to try to accomplish what I want here. Its close, but the longer you hold the up arrow, the faster the fuel drains:
public bool test = false;
if (Input.GetButtonDown ("Vertical") && yPosition < 5)
{
yPosition += 5;
test = true;
}
if (Input.GetButtonUp ("Vertical") && yPosition >= 5)
{
yPosition -= 5;
test = false;
}
void Update()
{
StartCoroutine (testCoroutine ())
}
IEnumerator testCorutine()
{
while (test == true)
{
fuel = Mathf.MoveTowards (fuel, 0, Time.fixedDeltaTime * 0.1f);
yield return null;
}
}
You’re starting a coroutine in the update function. So every single frame you’re starting up a new copy of the co routine.
When the buttons not held coroutines simply end immediately since test = false. When the button is held the coroutines keep running in the loop draining fuel. Except instead of just having 1 coroutine running draining fuel you’re adding more and more coroutines every frame, thus draining fuel faster and faster and faster until you let go of the button and all the coroutines end as test = false again.