Help with destroying enemies

Ok. So I made an enemy and made a few copies of it. Everything seemed fine. The enemies were following my character, but after I killed one of them and then clicked again to initiate another attack the game ended and I got this error.

MissingReferenceException: The object of type ‘GameObject’ has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
Here is the code I am using for the PlayerAttack.

using UnityEngine;
using System.Collections;

public class PlayerAttack : MonoBehaviour {
	public GameObject target;
	public float attackTimer;
	public float coolDown;

	// Use this for initialization
	void Start () {
		attackTimer = 0;
		coolDown = 0.2f;
	
	}
	
	// Update is called once per frame
	void Update () {
		if(attackTimer > 0)
			attackTimer -= Time.deltaTime;
		if(attackTimer < 0)
			attackTimer = 0;
		if(Input.GetKeyUp(KeyCode.Mouse0)){
			if(attackTimer == 0){
				
		    Attack();	
			attackTimer = coolDown;
		
		 
			}
				
			
		}
	
	}
	
	
	private void Attack(){
		float distance = Vector3.Distance(target.transform.position, transform.position);
		
		Vector3 dir = (target.transform.position - transform.position).normalized;
		
		float direction = Vector3.Dot(dir, transform.forward);
		
		Debug.Log (direction);
		if(distance < 2.5){
			if(direction > 0){
		EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");
		eh.AddJustCurrentHealth(-10);
		}
		}
	}
}

I have no idea how to work around this.

From what I understand you are setting the Enemy using the var target probably using the editor.

What happens now is that once you are killing that one, there isn’t another to take it’s place.

I don’t know how your game is setup (fps, 3ps, ranged weapons, melee), but if you want to continue this
way you need a way to determine which enemy you are attacking.

Usually people use collision detection. You might also want to use an auto-target (target-lock) feature (probably based
on distance). In any way you need a way of locating the current enemy.

Now if you post more details about your game we can be more helpful and provide a way that suits the gameplay you
want.

For example if you were using an auto-target system you would need to
create an array of gameobjects (based on tag most likely) and then go through
that array in a loop in order to find the closest one.

If you are doing a shoot em up you would most likely do a raycast and reduce the
health of the object returned by said raycast.

Anyway…

Ah, Ok Thanks. :slight_smile: