- Home /
Problem With Coroutine - Infinite Loop?
I'm making a 2D platformer in which the player can move onto a launch pad and press a combination of buttons to do a long jump. The long jump is executed by multiplying the player's x velocity by a constant when they're in the air, so they travel a greater distance before landing.
In the code below:
xmultiply is the constant that the player's x velocity is multiplied by
playerLongJumping is a bool that checks whether the player has pressed the required buttons to long jump
initialx is the player's position when they first begin to long jump (To prevent glitches, the player must automatically stop long jumping once they reach a certain displacement, 20, from the start position)
The IEnumerator coroutine is called in void Start.
When I enter play mode in the editor, the entire Unity editor freezes up as soon as the player tries to long jump, and I think it might have something to do with an infinite loop in that coroutine. How can I fix it to make it work as intended? Thanks a lot.
IEnumerator DoLongJump()
{
while (3 == 3) // Condition always true
{
xmultiply = 1;
while (playerLongJumping == false)
{
yield return null;
}
initialx = player.transform.position.x;
while (playerLongJumping == true && Mathf.Abs(player.transform.position.x - initialx) < 20f)
{
xmultiply = 2.7f;
}
}
}
Why are you forcing the Infinite loop? You are also probably creating 100s of this coroutine. One is created every time you hit the long jump button and this coroutine never exits.
How does it create hundreds of coroutines if this coroutine is only called once in void Start?
In that case it doesn't. I wasn't sure if you assigned it to the space bar input (or some other input). Thus every time you hit the spacebar you would do a long jump. :)
Answer by ecv80 · Dec 08, 2018 at 09:58 PM
It looks like you might not be setting playerLongJumping to false, after you set it to true. So when Mathf.Abs(player.transform.position.x - initialx) is equal or greater than 20, your while(3==3) loop goes to the next iteration but since playerLongJumping is not false and the next conditions aren't ever met again, it keeps looping without yielding ever again.
Personally, I don't like how you're handling any of this. I fail to see why you use loops instead of simple conditions and also why you would want a coroutine running all the time for this use case. But to each their own.
EDIT: Or it might just be that you're never yielding in your playerLongJumping == true && Mathf.Abs(player.transform.position.x - initialx) < 20f while loop as well.
Your answer
Follow this Question
Related Questions
making a 2D character Speak for different lenghts of time 2 Answers
How to prevent holding down a key to infinitely loop an action? 1 Answer
Line of code skips randomly at times? 1 Answer
Upon shooting, Raycast target moves infinitely 1 Answer
What's the most efficient method of implementing an infinite parallax background? 0 Answers