In my game, the power ups that the player can pick up, first check to see if the character is already powered up. If not, then it starts the coroutine called "FireBreathing" which handles the effects of the power up. If they are already powered up, I want to stop the coroutine and start it over so as to not have multiple of the same coroutines overlapping.
What I have here looks to me like it should work, but it doesn't. It will play through the coroutine like normal, but then when it's finished (either by just waiting for the coroutine to finish, or by getting another power up to restart the cycle) the coroutine won't start again.
type herepublic class StrawbiliEffect : MonoBehaviour
{
[SerializeField] float strawbiliMoveSpeed = 5f;
[SerializeField] float strawbiliJumpForce = 12f;
[SerializeField] float strawbiliDuration = 3f;
public bool isStrawbiliBoy;
IEnumerator coroutine;
AltPlayerController playerController;
Animator animator;
void Start()
{
playerController = GetComponent<AltPlayerController>();
coroutine = FireBreathing();
}
public void StrawbiliPowerUp()
{
Debug.Log("Function Called");
if (isStrawbiliBoy == false)
{
StartCoroutine(coroutine);
}
else if (isStrawbiliBoy == true)
{
StopCoroutine(coroutine);
Debug.Log("Coroutine stop attempted");
StartCoroutine(coroutine);
}
}
IEnumerator FireBreathing()
{
Debug.Log("Coroutine has started");
isStrawbiliBoy = true;
playerController.isNormalGerm = false;
playerController.moveSpeed = strawbiliMoveSpeed;
playerController.jumpForce = strawbiliJumpForce;
//animator.SetBool ("isStrawbiliBoy", true);
yield return new WaitForSeconds (strawbiliDuration);
//animator.SetBool ("isStrawbiliBoy", false);
playerController.isNormalGerm = true;
playerController.moveSpeed = playerController.normalMoveSpeed;
playerController.jumpForce = playerController.normalJumpForce;
isStrawbiliBoy = false;
Debug.Log("Coroutine has finished");
}
}
I move to collect the power up, and the console prints the "Function called" so I know the pick up method is still working fine. I've checked to make sure that all the bool variables switch back to the correct states. I just don't know what's wrong with it.
The thing is that before the second call, coroutine.MoveNext() would have returned false. Since the IEnumerator has reached the end.
In short, you need to use it a little differently.