Unable to execute a coroutine a second time, works fine the first time

Following on from my damage over time question, I now successfully have a damage over time script working fine.

Basically, you trigger the poisoned bool on the player to true and this will execute, do correct damage per second, finish and then set the bool back to false.

The weird thing is that once this is done, you can never set the bool back to true again, it immediately resets back to false.

If you stop and start the game, same again, works the first time then can never function again.

Please could someone educate me as to what is going on here?

using UnityEngine;
using System.Collections;

public class ScriptPlayerOnePoison : MonoBehaviour
{

    public float dmgTimer = 10;
    public float dmgAmount = 10;
    float dmgDecreaser = 1;                 // How much the dmg gets decreased by
    bool _poisonCoroutineRunning = false;   // Ensures ONE coroutine is running.
    ScriptPlayerOneManager script;

    void Start()
    {
        script = GameObject.Find("PrefabPlayerOne").GetComponent<ScriptPlayerOneManager>();
    }

    void Update()
    {
        CheckPoison();
    }

    void CheckPoison()
    {
        if (!_poisonCoroutineRunning && script.playerStatus.playerOnePoisoned) // IF you're poisoned and you aren't calculating any poison damage
        {
            _poisonCoroutineRunning = true;   // You lock yourself into 1 instance of the coroutine
            StartCoroutine(UpdatePoison());   // You start the coroutine
        }
    }

    IEnumerator UpdatePoison()
    {
        while (script.playerStatus.playerOnePoisoned && dmgTimer >= 0)     // While poisoned and the damage taken is greater than 0
        {
            script.playerActualAttributes.playerOneActualHealth -= dmgAmount;        // Drops health
            dmgTimer -= dmgDecreaser;                              // Drops damage

            yield return new WaitForSeconds(1);    // Waits 1 frame
        }// One of the conditions became false if it breaks past here

        script.playerStatus.playerOnePoisoned = false;
        _poisonCoroutineRunning = false;
        yield break;
    }
}

Many thanks!

Hard to say without the entire picture, however, most likely your conditions aren’t satisfied in the while statement of the UpdatePoison() function. To check this, the following line before the while line:

"Debug.Log("UpdatePoison() has been called: dmgTimer = " + dmgTimer + " PlayerPoisoned = " + script.playerStatus.playerOnePoisoned );"

This way you will know for sure when it is actually being called and what the variables are when the script is executed.

One thing I see, your dmgTimer never gets set to be above 0, therefor, your Coroutine will not run the while loop. The debug line should confirm this.

Excellent, thank you I figured it out, you were bang on about it not being reset to the original value upon completion :slight_smile: