How to create a link between HealthScript and HealtBar script ?

Hi everyone!

The thing I would like to do is that when my health points’ player go down, its health bar goes down too. But I don’t know how can I do. Maybe something like create a “link” between these two scripts…? I’m novice in scripting…

These are my HealthScript and my HealthBar script:

using UnityEngine;

public class HealthScript : MonoBehaviour
{

public int hp = 5;

public bool isEnemy = true;

void OnTriggerEnter2D(Collider2D collider)
{
    
    ShotScript shot = collider.gameObject.GetComponent<ShotScript>();
    if (shot != null)
    {
        
        if (shot.isEnemyShot != isEnemy)
        {
            hp -= shot.damage;

          
            Destroy(shot.gameObject);

            if (hp <= 0)
            {
                
                Destroy(gameObject);
            }
        }
    }
}

}

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;

public class HealthBar : MonoBehaviour {

#region Attributes

public GameObject healthBar;
public Color goodColor;
public Color middleColor;
public Color badColor;

#endregion

#region Unity methods

void Start()
{
    SetColor();
}

#endregion

#region Other methods

public void SetDamages(float value)
{
	healthBar.GetComponent<Scrollbar>().size -= value;

    float totalValue = healthBar.GetComponent<Scrollbar>().size;

    SetColor(totalValue);
}

void SetColor(float value = 1)
{
    if(value >= 0.5f)
    {
        healthBar.transform.FindChild("Mask").FindChild("Sprite").GetComponent<Image>().color = goodColor;
    }
    else if(value >= 0.25f && value < 0.5f)
    {
        healthBar.transform.FindChild("Mask").FindChild("Sprite").GetComponent<Image>().color = middleColor;
    }
    else
    {
        healthBar.transform.FindChild("Mask").FindChild("Sprite").GetComponent<Image>().color = badColor;
    }
}

#endregion

}

Could someone help me please? :slight_smile:

Create a variable for the health bar in the HealthScript like this:

public HealthBar healthBar;

Then assign it in the inspector.

         if (hp <= 0)
         {
             Destroy(healthBar.gameObject);
             Destroy(gameObject);
         }