Help with Health Damage script!

Im trying to make a script that you attach to a cube, and when you run into it, it lowers the health gui. I have already made a health system for my health, but i want to have something like this to test damage before i try to put it in ai. here’s my health bar script:

var Health : int = 100;
var BarGUI : GUIStyle;
var BorderGUI : GUIStyle;
var X : float;
var Y : float;
var RRect1 : float = 39.98;
var RRect2 : float = 1.19;
var RRect3 : float = 4.86;
var RRect4 : float = 10.5;
var RRect5 : float = 39.98;
var RRect6 : float = 1.19;
var RRect7 : float = 4.86;
var RRect8 : float = 10.5;

function OnGUI ()
{
	GUI.Label(new Rect(Screen.width/RRect1, Screen.height/RRect2, Screen.width/RRect3, Screen.height/RRect4)
		,""+Health+"%", BorderGUI);
	GUI.Label(new Rect(Screen.width/RRect5, Screen.height/RRect6, Screen.width/RRect7, Screen.height/RRect8)
		,""+Health+"", BarGUI);
}

function Update ()
{
	Y = Health;
	X = Y / 100;
	RRect7 = 4.86 / X;
	
	if(Health < 0)
	{
		Health = 0;
	}
	if(Health > 100)
	{
		Health = 100;
	}
}

Now that i see it in the preview it looks different but it should work all the same. Keep in mind that the script works, and when i change the value of the health, it lowers the bar and the percentage on the GUI. The var RRect’s are for the placement on the screen. Please help me figure it out if you can. Thanks

You can add a collider to the cube and then set up an OnTriggerEnter function in a script attached to it. Here is the tutorial on setting up GameObjects for collisions although there are plenty available a Google search away:

Collider tutorial

The logic on the cube script should contain something like this, I wrote it in C# but the logic should be the same.

public class Cube : MonoBehaviour {
    void OnTriggerEnter(Collider other) {
        //GetComponent will fetch the HealthBarScript if it is on the cube, otherwise
        //you could use FindObjectByType or have a direct reference on the cube too
        GetComponent<HealthBarScript>().DepleteHealth();
    }
}

In the HealthBarScript you will need a function that depletes the health, something like this

    public void DepleteHealth() {
        Health -= 10;
    }

It might be worth putting some debug statements inside the OnTriggerEnter function initially to ensure you have the colliders configured properly.