How can I Update HealthUI when the object is destroyed.

I have a Script called Player.cs and inside of it there is a public class called PlayerStats with a health integer.

public class Player : Monobehaviour{
             [System.Serializable]
             public class PlayerStats
             {
                  public int Health = 100;
             }
        }

and I also have a class Health UI called HealthUI.cs with a UItext

        public class HealthUI : Monobehaviour
        {
             Text text;
             private static int health;
             private Player player
        
             void Start()
             {
             text = GetComponent <Text> ();
             player =(Player)GameObject.FindGameObjectWithTag("Player").
             GetComponent(typeof(Player));
             }
             void Update()
             {
             health = player.playerStats.Health;
             text.text = "Health" + health;
`           `}
    }

My problem is :

  1. In Scene, the UI text (Health : 100) and subtracting my health works. But when my object is destroyed and spawns again, my HealthUI doesnt reset to 100 and stops to work.

  2. How can I limit my health to 0 minimum number and 100 as maximum number?

Please help :slight_smile:

  1. Your object is deleted. So it will terminate the script there.
    2)Mathf.Clamp is good… But I would have two variables. One for Max and Min and use some Boolean like if x >= max to control it. That way you can extend functionality come time if you want to add power ups to your game or something.

But Mathf.Clamp is definite good.

Regarding your problems:

my HealthUI doesnt reset to 100

This is probably because of this code:

private static int health;

Your health variable is static so it do not rely on instances. To reset health on a new instance your Start function should look like:

  void Start()
  {
     text = GetComponent <Text> ();
     player =(Player)GameObject.FindGameObjectWithTag("Player").
     GetComponent(typeof(Player));
     health = 100;  // <----------------reset the value here
  }

How can I limit my health to 0 minimum number and 100 as maximum number?

Regarding this problem you can either use Mathf.Clamp or try with Mathf.Max and Mathf.Min together, to limit the health values.

Hope it helps!