Hi, So i am wanting to reduce an enemies health from a script I have attached to my Bullet Object, I have the health of the enemy attached to the enemy object. But I am having some problems with how this is working. First problem is, when the bullet is colliding the the enemy, it seems to reduce the health twice, can it be that the collision is registering twice before the bullet is destroyed? The second problem is I cant get the enemy to destroy after the health reaches 0. I have the code for the deletion back in the enemy script, does the variable not pass between the two scripts so the enemy script knows when the health = 0?
Bullet script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletOnHit : MonoBehaviour {
public GameObject Enemy;
private Lvl1Enemy EnemyHealthScript;
private int EnemyHealth;
private void Start()
{
EnemyHealthScript = Enemy.GetComponent<Lvl1Enemy>();
EnemyHealth = EnemyHealthScript.Health;
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Enemy")
{
Debug.Log("Hit");
EnemyHealth -=50;
Destroy(this.gameObject);
Debug.Log("Health = " + EnemyHealth);
}
if (other.gameObject.tag == "Wall")
{
Debug.Log("Wall Hit");
Destroy(this.gameObject);
}
}
}
Enemy health script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Lvl1Enemy : MonoBehaviour {
public int Health = 100;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if (Health <= 0)
{
Destroy(this.gameObject);
}
Debug.Log("Health = " + Health);
}
}
If anyone could help with this, it would be greatly appreciated