I have a simple script to keep track of a public HP variable and it also has a function Apply1Damage() that reduces HP by 1 everytime it is called. I also have a script which SendMessage() when a collision or a trigger is detected (OnTriggerEnter, OnCollisionEnter).
I have applied the HP script to my enemies object and it works perfectly. However, when I apply the same script to my player object, the HP variable keep resetting to the initial value at a very fast speed. Using Debug.Log, I see that my player is receiving the damage and that the health variable is being reduced, but never less than the initial value-1.
What could be causing this?
Here are the relevant scripts:
public class DamageableMonster : MonoBehaviour {
public float health;
Animator damageableObjectAnimator;
void Start()
{
damageableObjectAnimator = GetComponent<Animator>();
}
void apply1Damage()
{
health--;
Debug.Log("Health down to: " + health);
}
void Update () {
if (health <= 0)
{
damageableObjectAnimator.SetTrigger("Death");
}
}
}
And
public class Apply1Damage : MonoBehaviour {
public float knockback;
// Use this for initialization
void Start () {
knockback = 1000;
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.layer != 8)
{
Debug.Log("HIT");
float xDistance = (other.transform.position.x - gameObject.GetComponentInParent<Transform>().position.x);
float yDistance = (other.transform.position.y - gameObject.GetComponentInParent<Transform>().position.y);
other.collider.SendMessage("apply1Damage");
other.rigidbody.AddForce(new Vector2(xDistance * knockback, yDistance * knockback));
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.layer != 8)
{
Debug.Log("HIT");
float xDistance = (other.transform.position.x - gameObject.GetComponentInParent<Transform>().position.x);
float yDistance = (other.transform.position.y - gameObject.GetComponentInParent<Transform>().position.y);
other.SendMessage("apply1Damage");
other.GetComponent<Rigidbody2D>().AddForce(new Vector2(xDistance * knockback, yDistance * knockback));
}
}
}