Hi @Toff1n ,
I think the error comes from this line:
EnemyController enemy = GameObject.FindGameObjectWithTag("Enemy").GetComponent();
So, lets a bullet hits and object, when this happens the bullet reads the object’s tag to check if it is an enemy. Then, if it is an enemy, you destroy the bullet (this is ok) and you create an enemy variable which will look on the entire scene trying to find an object with the tag you want (“Enemy” in this case). As you say, there are more than one enemy, so the script will find more than one enemy. Why would you do that? If you are hitting the right enemy you want to reduce health to, you should use this (as you did at the beginning of this question):
enemy = hit.gameObject.GetComponent ();
That would reduce health to those enemies who got hit by that bullet (one if the bullet is destroyed).
Now, the enemy script should have a public variable called health, otherwise you won’t be able to reduce its health.
NOTE: This is not the best way of reducing enemies health. I recommend you to create a public event (i.e. called ReduceHealth()) with an imput parameter that we will use to calculate the amount of health we have to reduce). This way, the one who calculate the amount of damage is the enemy and not each bullet. So in your EnemyController script you should have an event like this:
public void ReduceHealth(int damage)
{
//This is a simple way of reducing an enemy's health. You could create a more complicated script to calculate this damage, based on armor for example.
health -= damage;
}
Once you have this, your script should look like this:
public float speed;
private float timeAlive;
public GameObject player;
private GunController gun;
void Start () {
player = GameObject.Find ("Player");
gun = player.GetComponent <GunController> ();
}
void Update () {
BulletHandler ();
}
void OnTriggerEnter (Collider hit) {
if (hit.tag == "Enemy") {
Debug.Log ("Hit " + hit.name);
EnemyController enemy = hit.gameObject.GetComponent<EnemyController>();
enemy.ReduceHealth(gun.damage);
Destroy (this.gameObject);
}
}
void BulletHandler () {
transform.Translate (Vector2.right * speed * Time.deltaTime);
timeAlive += Time.deltaTime;
if (timeAlive > 2) {
Destroy (this.gameObject);
}
}
That should work. If it doesn’t, I suggest you to upload the exact console output of the error, that way I could further help you.