This little bit of code is causing very bad performance when I have lots of gameobjects tagged as “Enemy” with the script that the follow code is from attached:
GameObject[] Zombies = GameObject.FindGameObjectsWithTag("Enemy");
foreach(GameObject ZombieObj in Zombies)
{
Vector3 DirectionToZombie = ZombieObj.transform.position - transform.position;
float DistanceToZombie = DirectionToZombie.magnitude;
Zombie Zombie = ZombieObj.GetComponent<Zombie>();
if(DistanceToZombie < ZombieRecruitmentRange && Zombie.IsHostile == true && Zombie.CanRecruit == true && DistanceToTarget < ZombiesStopRecruitingDistance)
{
IsHostile = true;
HostileTimer = HostileCoolTime;
}
}
I am trying to find if a nearby zombie is hostile and within range to make an unhostile zombie turn hostile. Currently with this code I am checking every single zombie gameobject in the game tagged “enemy” and then checking if it is within range to make it hostile. This is causing bad performance because every single zombie is checking for every single other zombie, causing exponential performance loss. However I don’t know another way to get the same functionality with better performance. I think I need to check if there is a gameobject tagged “Enemy” in range first, instead of checking every gameobject and then checking if it is in range, but I don’t know how to do this in code.