Lose and gain health when collision happens?

So I have two blocks. One depletes the player’s health and the other one replenishes it. I have looked around for help on doing just that when I touch the blocks with my character, but am at a standstill. I have put print code inside my function to test if it is even going through, but it isn’t. Could you help me out here?

Code:

#pragma strict

var health : float = 100;
var isBad : boolean = false;

function OnCollisionEnter(collision : Collision)
{	
	if (collision.gameObject.CompareTag("Player"))
	{
		if(isBad == true)
		{
			health -= .5;
			print("Lose");
		}
		else if (isBad == false)
		{
			health += .5;
			print ("Gain");
		}
	}
}

function OnGUI()
{
	GUI.Label(Rect(10,10,100,20),health.ToString());
}

I took the liberty of recreating your project as you described it here. I made a slight change you your code, and it worked for me. Here is the new code

#pragma strict
 
var health : float = 100;
var isBad : boolean = false;
 
function OnTriggerEnter(other : Collider)
{   
    if (other.tag == "Player")
    {
        if(isBad == true)
        {
            health -= .5;
            print("Lose");
        }
        else if (isBad == false)
        {
            health += .5;
            print ("Gain");
        }
    }
}
 
function OnGUI()
{
    GUI.Label(Rect(10,10,100,20),health.ToString());
}

I changed your OnCollisionEnter() to OnTriggerEnter() and changed the check for player. When I tried it, the GUI looked a little wacky, but that’s outside of the scope of your question. To add this, you’ll just need to mark your boxes as trigger, and you should be golden.

First you might have to add a rigidbody to both objects(if you do not already have) and then if you are using the collider as a Trigger if it shouldn’t collide physically with other bodies, in that case you need to change function to OnTriggerEnter And change is Trigger to true on the collider.

One last thing I’d try out is to change the tag comparison to something like this:

if (collision.gameObject.tag == "Player")

Just to make sure that isn’t the problem.

One note too is that OnCollisionEnter fires only once when a body enters the collider, use OnCollisionStay or OnTriggerStay for continuous fire of the function.