Variable not resetting on keyup
Hello. If i hold button for not very long the power is set to 1. If i hold button long enough to get 5 power it resets to 0 as is in code. Why its not resetting to 0 every time I release button?
void Start()
{
secondsHeld = 0.0f;
buttonReleased = true;
}
void Update()
{
powerText.text = "Power: " + secondsHeld;
if (Input.GetKeyDown(KeyCode.Space))
{
buttonReleased = !buttonReleased;
StartCoroutine(HowLongButtonWasHeld());
}
if (Input.GetKeyUp(KeyCode.Space))
{
buttonReleased = !buttonReleased;
float forceToAdd = secondsHeld * ballSpeed;
SpawnBall(forceToAdd);
secondsHeld = 0.0f;
}
}
IEnumerator HowLongButtonWasHeld()
{
while (secondsHeld < 5 && !buttonReleased)
{
yield return new WaitForSeconds(0.4f);
secondsHeld++;
}
Answer by Hellium · Feb 17, 2021 at 10:24 PM
Most likely because you don't abort the coroutine.
But in your case, I don't see why you use a coroutine.
void Start()
{
secondsHeld = 0.0f;
}
void Update()
{
if (Input.GetKey(KeyCode.Space) && secondsHeld < 5)
{
secondsHeld = Mathf.Min(secondsHeld + Time.deltaTime, 5);
powerText.text = "Power: " + ((int) secondsHeld);
}
else if (Input.GetKeyUp(KeyCode.Space))
{
float forceToAdd = secondsHeld * ballSpeed;
SpawnBall(forceToAdd);
secondsHeld = 0.0f;
}
}
Thanks. I have another question. I put StopAllCourutines() right after resetting secondsheld to 0 and it works. But when i put StopCourutine(HowLongButtonWasHeld()) it doesnt cancel it. What is the problem?
Your answer
Follow this Question
Related Questions
Traffic Light won't change colors State machine 0 Answers
Start coroutines when the class is not a MonoBehaviour 1 Answer
"Can't add script behaviour AICharacterControl. The script needs to derive from MonoBehaviour!" ? 0 Answers
WaitForSeconds in Coroutines do not work. 0 Answers
Where and how should I stop the counter when the while loop is ended ? 0 Answers