- Home /
grab all game objects with a distance of the object?
i was wondering if there was a way to grab every single object in a certain distance from an object (like if the range is 30, then every object that is 30 units or less away is used in the function).
what i want to do is add this to my bomb, i already have it set up to explode and all that, i just want it to say something like
if(Vector3.Distance(stuff in here to get distance)
later I'll add in some stuff saying like the farther you are from it the less damage you take, but for now just answer the question please :)
Answer by Lipis · Mar 11, 2010 at 01:37 AM
Even though probably this is not the most efficient way of doing something like that, I guess you want something like this:
allObjects = FindObjectsOfType (GameObject);
for (var child : GameObject in allObjects) {
dist = (transform.position - child.transform.position).magnitude;
if (dist < 30) {
Debug.Log(child.name + ": " + dist);
}
}
To get the distance between two points in Unity you can use magnitude
. If you only need to compare magnitudes of some vectors, you can compare squared magnitudes of them using sqrMagnitude
, because computing squared magnitudes is faster.
Another way (and more efficient one) of achieving that is to use Physics.OverlapSphere
, which returns an array with all colliders touching or inside the sphere, by providing the position
and a radius
.
Answer by hellowill89 · Nov 06, 2017 at 04:49 PM
Use OverlapSphere instead. Much better way to do it.