I need to find game objects with a distance of ‘x’ from the current game object.
GameObject.Find functions does not give this feasibility to me.
If there any other way to achieve this ?
Ex: I have my hero who is surrounded by ‘n’ number of enemies.
I need to find out number of enemies at 1 unit distance. Any body can help me with this problem ?
Er - ok, you hadn’t really been clear up to this point.
Assuming that the GameObjects in question have colliders attached to them-
// returns an array of objects within radius of origin or null
// if nothing is nearby
public GameObject[] GetNearby(Vector3 origin, float radius)
{
Collider[] cols = Physics.OverlapSphere(origin, radius);
if (cols.Length > 0)
{
GameObject[] nearby = new GameObject[cols.Length];
for (var i = 0; i < cols.Length; i++)
{
nearby[i] = cols[i].gameObject;
}
return nearby;
}
return null;
}
Of course, if you didn’t want the abstraction just use the Physics method directly
// find everything around me within 10 meters
Colider[] nearby = Physics.OverlapSphere(transform.position, 10);
for (var i = 0; i < nearby.Length; i++)
{
// do something awesome
}
Whenever you need to find objects that are within a certain distance of something. Idle units in our game - Fractured State - use it as a sort of “radar ping” to see if any enemies are nearby. We use that instead of a collider trigger so that it doesn’t get evaluated constantly and can stay in step with our line of sight evaluations (via a Coroutine).
I’ve also seen it used as a local avoidance method in steering behaviors.
i know this was 10 years ago lol, but in case anyone gets to this post, if you want to filter a certain kind of gameobjects its better to use a list for the objects nearby and then use.ToArray().
this way you’ll get only the gameobjects with the EnemieClass Component in your enemiesInRange array, instead of getting a lot of empty gameobjects if you used an array as nearby.
There’s no good reason to necro a thread, especially one that’s 10 years old. Please don’t do this.
Also, what you’ve posted here isn’t really good advice TBH.
You’re generating both an array and a list just to get some objects. That’s extremely wasteful and will produce a lot of GC waste. This is why OverlapSphereNonAlloc exists. In the very least, you should be passing in the list so it’s reused rather than producing a new one each call. You could also just step through the array and if something isn’t relevant then simply move the final entry to this entry and reduce the count to look at in the array returning the array and how many entries are valid. Finally, it’d be better to organise your project so that enemy are on a layer and you’d only expect that component on such things therefore specifying the enemy layer in the query will always give you the correct results; not always possible in more complex games but certainly the best option if available.
There’s lots of better ways beyond creating more GC waste.