If Check Colliding GameObject Variable

I’m looking for a way to check a variable in the script of a gameObject my player is colliding with. Here is what I currently have:

void OnCollisionEnter(Collision collision)
	{
		if(collision.gameObject.tag == "Enemy")
		{
			hitPoints = hitPoints - 1;
		}
	}

What I want is for “hitPoints = hitPoints - 1;” to fire only if the colliding gameObject has the tag “Enemy” and if that specific Enemy instance’s own hit points variable is above zero. How would I do that?

You need to get a reference to the other object’s script using GetComponent, then you can access the variable provided it’s public.

void OnCollisionEnter(Collision collision)
{
  if(collision.gameObject.tag == "Enemy")
  {
    EnemyScript enemy = collision.gameObject.GetComponent<EnemyScript>();
    if(enemy != null && enemy.hitPoints > 0)
    {
      hitPoints -= 1;
    }
  }
}

Replace ‘EnemyScript’ with whatever you call your enemy’s script.