Multiple Enemies but only one is shooting

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

{

 projectileSpawn = this.transform.parent.GetChild(0).position;

 rotation = this.transform.parent.GetChild(0).rotation;

 ShootProjectile();

}

private void OnTriggerStay(Collider collision)

{

 if (collision.tag == "Human")

 {
     targeter = GameObject.Find("Human-1").transform;

     GameObject.Find("ProjectileSpawn").GetComponent<TurretEnemy>().SetInRange(true); 

     //SetInRange(true);

     Debug.Log("In range of enemy turret");

}

else if (collision.tag == “Human2”) {

     targeter = GameObject.Find("Human-2").transform;

     GameObject.Find("ProjectileSpawn").GetComponent<TurretEnemy>().SetInRange(true);

     //SetInRange(true);
     Debug.Log("In range of enemy turret");
 }

}

private void OnTriggerExit(Collider collision)

{

   if (collision.tag == "Human2" || collision.tag == "Human")

   {
     GameObject.Find("ProjectileSpawn").GetComponent<TurretAI>().SetInRange(false);

    // SetInRange(false);
     target = null;

     Debug.Log("Out of range of enemy turret");

}

} // Resets the value of TurretAI.inRange to false when the astral goes out of range (leaves box collider)

private void ShootProjectile()

{
if (inRange && Time.time > nextShot) // Provided the target is close enough and a set time has past since the last shot, shoot at target
{

     nextShot = Time.time + fireRate; // Causes a time delay between each projectile being fired

Instantiate(projectile, projectileSpawn, rotation);

     Debug.Log("Shots Fired!");
 }

}
private void SetInRange(bool incomingValue)
{
inRange = incomingValue;
}

My initial thought is your code is Finding only 1 of the the “ProjectileSpawn” because they are called the same on all enemies. Try changing the names (ProjectileSpawn1 and ProjectileSpawn2).

@RustyCrow How would I make it modular because the gameObject is attached to each instance of the enemy and renaming it would make a bunch of extra code scripts when I need it to be modular

Hey there,

RustyCrow definitely has the right idea here. What’s happening is all your enemies are finding the same object, because they all have the same name and GameObject.Find() doesn’t care whether that object is attached to it or not; it just returns the first one it finds.

What you want to do here is replace that line with:

GetComponentInChildren<TurretAI>().SetInRange(true);

This is assuming that you only have 1 TurretAI per object holding that script, and that it is a child of it.
If the TurretAI script is attached to the same object as your Enemy script, simply remove the “InChildren” from my line above.


Hope that helps!

Cheers,

~LegendBacon