- Home /
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 :)
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;
}
}
Answer by alwayscodeangry · Jul 13, 2014 at 12:04 PM
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.
Answer by NerdRageStudios · Jul 13, 2014 at 12:53 PM
That's fantastic, thank you very much, it worked a treat :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613153939im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to disable a script on a bunch of instantiated objects with tag ? 1 Answer
Performance issues with GetComponent/gameObject.Find in different functions 1 Answer
Powerup issue - Speed 1 Answer
Yield WaitForSeconds Not Working. Coroutine. 1 Answer
Damager Powerup issue - NullReferenceException: Object reference not set to an instance of an object 2 Answers