Temporary Buff scripts and timers

Hi all, I am using the following script to add a set amount of health to the player for 30 seconds.

When I press β€œ2” to test it the script works fine, I see the buff apply, then disappear, however if I run it again the buff applies but never disappears again (its like the timer only functions once)

Also, I cant figure out how to stop this from stacking if I keep triggering it.

Any help on this would be greatly appreciated :slight_smile:

using UnityEngine;
using System.Collections;

public class ScriptTempHealthBuff : MonoBehaviour {

    ScriptPlayerOneManager script;
  
    public int healthBuffAmount = 30;
    public int healthBuffDuration = 5;

	// Use this for initialization
	void Start () {
    script = GameObject.Find("GameObjectPlayerOne").GetComponent<ScriptPlayerOneManager>();
    StartCoroutine(playerHealthBuffTimer());

	}
	
	// Update is called once per frame
	void Update () {

        if (Input.GetKeyDown("2"))
        {
        script.playerTempAttributes.playerOneTempHealth += healthBuffAmount;
        playerHealthBuffTimer();
        }
     
	}

    // Now run a timer
    IEnumerator playerHealthBuffTimer()
    {
        yield return new WaitForSeconds(healthBuffDuration);
        playerHealthBuffUndo();
    }

    //Now return the value back to original
    void playerHealthBuffUndo()
    {
        script.playerTempAttributes.playerOneTempHealth -= healthBuffAmount;
    }
}

I think your first problem is on line 24, you should be calling StartCoroutine(playerHealthBuffTimer()); (I make this mistake all the time :P)

Are you aware you’re calling the coroutine in Start() as well?

To fix the stacking issue, just add a bool field, set it to true when you start the timer, set it to false when the timer ends, and check that it is false before activating the buff.

That’s fantastic, thank you very much, it worked a treat :slight_smile: