- Home /
How do I call this function once in update?
Hey, so basically, i'm trying to make an armor script, i want this script to add maxhealth to my character once, then deactivate my boolean so it doesnt give my player more maxhealth, but this doesn't seem to be working and just keeps adding maxhealth to my character infinitely. Is there something i've done wrong?
public int health;
public int protection;
public GameObject armor;
public Player player;
private Enemy enemy;
public ArmorHandler handler;
public bool hasAdded = false;
private void Start()
{
enemy = GameObject.FindGameObjectWithTag("Enemy").GetComponent<Enemy>();
}
private void Update()
{
if (armor.activeInHierarchy == true)
{
if(hasAdded == false)
{
AddStats();
hasAdded = true;
}
}
}
public void AddStats()
{
if (!hasAdded)
{
player.maxHealth += health;
enemy.dealDamage -= protection;
handler.protection += protection;
hasAdded = true;
}
}
Answer by Crown3d · Jun 24, 2021 at 02:58 AM
Remove hasAdded from the AddStats function. You only need to turn it true once. As for the loop something else in your code has to be turning hasAdded to false. I'd check all script that affect that bool.
Answer by WakingDragon · Jun 24, 2021 at 09:21 AM
Apart from the double-use of "hasAdded = true", this code works. Somewhere else in your code there is a problem. Or the architecture is wrong.
You say you only want to trigger this function once, so I would make it a public function that responds to an event like OnTriggerEnter (if the player is collecting loot) or response to user input (if being selected from an inventory). That stops the code from polling every frame for something that it does not need to.
You might also want to set your hasAdded bool to private and create a get/set function which will prevent you from accidentally referencing the variable from somewhere else. That will also allow you to put a Debug.Log statement into the get/set function so you can see when it is being called.
Your answer
![](https://koobas.hobune.stream/wayback/20220613035423im_/https://answers.unity.com/themes/thub/images/avi.jpg)