- Home /
Question by
ugurgulser · Sep 30, 2020 at 10:37 AM ·
arraylistclosest
How To Find the Closest Object
Hello,
My game is 2D.
I have AI bots. They have to detect other bots(tag=bot), collectible items(tag=collectible) and our player(tag = player).
And it must find the closest object. And if any bots gets near a bot, the bot must detect if other bot is stronger than it(float power) and change the target.
I was using that code for finding closest object:
public GameObject GetClosestObject()
{
allTargets = null;
orbits = GameObject.FindGameObjectsWithTag("OrbitBoost");
enemies = GameObject.FindGameObjectsWithTag("Enemy");
allTargets = orbits.Concat(enemies).ToArray();
float closest = 999999; //add your max range here
for (int i = 0; i < allTargets.Length; i++) //list of gameObjects to search through
{
float dist = Vector3.Distance(allTargets[i].transform.position, this.transform.position);
if (dist < closest)
{
closest = dist;
target = allTargets[i];
}
}
return target;
}
But this code did not help me about if a bots gets near other bot and change the target. It always gets the closest object (including collectibles).
How can I do that?
Comment