Issue with coroutine
Hi all. I'm having a bit of trouble with a coroutine and after looking for a long time, I still can't find the issue, so I'm hoping one of you kind devs will be able to figure it out for me. :D So I have a coroutine which I use to change the Y coordinate of the player depending on the direction they moved last. Here's the [art of my code that isn't working like it should.
private void DelayedUpdate()
{
if (node.currentNode != null)
{
if (node.currentNode.inJumperRadius == true && PlayerMovement.playerMoved == true && Node.jumperRadiusToJumper == true)
{
Debug.Log("start");
StartCoroutine(InJumperRadius());
Node.jumperRadiusToJumper = false;
return;
}
if (node.currentNode.inJumperRadius == false && node.currentNode.jumper == false)
{
Node.jumpInProgress = false;
}
}
}
IEnumerator InJumperRadius()
{
while (node.currentNode.inJumperRadius == true)
{
yield return null;
}
if (node.currentNode.canJumpDown == true && PlayerMovement.lastMoveDir == "Down")
{
Debug.Log("that1");
PlayerMovement.changeYBy = "Up";
Node.canJump = false;
Camera.enableArrows = false;
Node.jumperRadiusToJumper = true;
//yield break;
}
if (node.currentNode.canJumpRight == true && PlayerMovement.lastMoveDir == "Right")
{
Debug.Log("that2");
PlayerMovement.changeYBy = "Up";
Node.canJump = false;
Camera.enableArrows = false;
Node.jumperRadiusToJumper = true;
//yield break;
}
if (node.currentNode.canJumpLeft == true && PlayerMovement.lastMoveDir == "Left")
{
Debug.Log("that3");
PlayerMovement.changeYBy = "Up";
Node.canJump = false;
Camera.enableArrows = false;
Node.jumperRadiusToJumper = true;
//yield break;
}
if (node.currentNode.canJumpUp == true && PlayerMovement.lastMoveDir == "Up")
{
Debug.Log("that4");
PlayerMovement.changeYBy = "Up";
Node.canJump = false;
Camera.enableArrows = false;
Node.jumperRadiusToJumper = true;
//yield break;
}
Node.jumperRadiusToJumper = true;
}
What is happening is the code under the 'while loop' in the coroutine is sometimes called twice or more than twice. Yes, sometimes, so it is also only called once like it should be called sometimes. Having this part called more than once causes issues with my game, making the player move up more levels than I want him to. As you can see the coroutine is called from my 'DelayedUpdate()' function using InvokeRepeating. This is the only place the coroutine is called from.
I have also made use of 'Debug.Log' to debug where the problem lies, and that is in the coroutine. To make it a bit clearer using an example, 'start' is outputted to the console once, and 'that1' is outputted to the console twice. This is how I know the error is not in 'DelayedUpdate()'.
I really hope someone could figure out what the problem is because this is not how a coroutine should work. Thanks!