Hello. I am making a tower defence game for learning and i want to add health for my enemy cube and it does work it destroy the gameobject but it should decrease health from 100 to 50 then 0 and print me test but it does not work the health does not decrease i think i see because its public. Why its not decreasing? the if (ehealth < 1) was in update void too still the same problem.
Currently, you’re destroying the Game Object on the first hit, not the second.
public class EnemyHealth : MonoBehaviour {
public float ehealth = 100f;
void OnCollisionEnter (Collision col)
{
if(col.gameObject.name == "Enemy")
{
ehealth -= 50f;
Destroy(col.gameObject); //This destroys the object that hit it.
if (ehealth < 1) {
Destroy (gameObject); //This destroys the game object that has this script attached.
print ("test. SHOULD PRINT NOW");
}
}
}
}
Also, a few other recommendations:
Consider using int instead of float if you only plan on using integers for ehealth. Just remember to remove the ‘f’ from any numbers (such as the 50f or 100f)
Consider using the tag system (and tag all enemies appropriately) instead of the name of the game object. Information on how to use tags can be found here. If you were using tags, the conditional on your if statement would change tocol.gameObject.tag == "Enemy"
Check if the eHealth value in the inspector is actually 100. Remember that public variables that have their values changed in the script won’t reflect those changes on the gameObject (until the component is reset or newly added).
Other than that, I understand that this script is on your enemy cube objects. Why does the OnCollisionEnter function check if the objects this cube enemy is colliding with is also an enemy? (-> if(col.gameObject.name == “Enemy”)) ? That would mean that if two enemies collide, both would lose health.