bullets kill all enemies, not just the ones hit.

Hi all, I have several enemies walking around my level chasing the player but when I shoot one, all of them take damage.

Here is my code attached to my bullet prefab

public class Bullet : MonoBehaviour {

	public float lifeSpan = 3;
	static private Enemy myEnemy;


	// Use this for initialization
	void Start () {

		gameObject.GetComponent<CapsuleCollider>().isTrigger = true;
		StartCoroutine(kill());

		if ((myEnemy = GameObject.FindObjectOfType(typeof(Enemy)) as Enemy) ==null)

		{
			Debug.Log("No Enemies to Shoot!!");
		}
	
	}

	void OnTriggerEnter(Collider other)

	{
		if(myEnemy !=null)

		{

		if	(other.gameObject.tag == "Enemy")

			{
				Debug.Log("Hit! " + other.name);
				myEnemy.takeDamage(10);
				Die();
			}

			else

			{
				Debug.Log ("Hit! " + other.name);
				Die();
			}
		}

	}
	// Update is called once per frame
	void Update () {
	
	}

	void Die()

	{

		Destroy(this.gameObject);
	}

	protected IEnumerator kill()
	{
		yield return new WaitForSeconds(lifeSpan);
		Destroy(gameObject);
	}
}

and here is my code attacked to my enemy…

public class Enemy : MonoBehaviour {

static private Player mainPlayer;
public enum EnemyType{Green, Purple, Red};
public float mHealth = 20.0f;
private float mMaxHealth = 20.0f;
[SerializeField]
private EnemyType enemyType = EnemyType.Purple;

void Awake()
	
{
	if(mainPlayer == null)
	{
		
		if((mainPlayer = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>()) == null)
		{
			if((mainPlayer = GameObject.FindObjectOfType(typeof(Player)) as Player) == null)
			{
				Debug.LogError("Cannot locate main player");
			}
		}
	}
}

public void takeDamage(float amount)
	
{
	mHealth -= amount;
	
	if(mHealth <=0)
		
	{
		dieEnemy();
	}
	
	
}

// Use this for initialization
void Start () {
	initEnemy(enemyType);
}

// Update is called once per frame
void Update () {




}

public void dieEnemy ()
{
	Destroy (gameObject);
}

public void initEnemy(EnemyType newEnemyType)
{
	switch(newEnemyType)
	{
	case EnemyType.Purple:
		mHealth = 20.0f;
		mMaxHealth = 15.0f;
		break;
	case EnemyType.Green:
		
		mHealth = 20.0f;
		mMaxHealth = 20.0f;
		break;
		
	case EnemyType.Red:
		
		mHealth = 20.0f;
		mMaxHealth = 10.0f;
		break;
		
	}
	
}

}

Can anyone tell me why this is happening?

TIA.

Try changing this:


if    (other.gameObject.tag == "Enemy")
 
         {
          Debug.Log("Hit! " + other.name);

to this:


if (other.gameObject.tag == "Enemy")
{
     myEnemy = other.gameObject.GetComponent<Enemy>();
     Debug.Log("Hit! " + other.name);

As far as I can tell, you’re not telling the specific enemy to die when colliding.

On a side note, you can change lines like this:


if ((myEnemy = GameObject.FindObjectOfType(typeof(Enemy)) as Enemy) ==null)

to something like this:


if (GameObject.FindObjectOfType<Enemy>() == null)

Hope this helps!