x


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 :)

more ▼

asked Mar 10 '10 at 11:17 PM

Adam Bruns gravatar image

Adam Bruns
274 24 27 38

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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.

more ▼

answered Mar 11 '10 at 01:37 AM

Lipis gravatar image

Lipis
2.3k 10 22 48

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x5076
x2086
x374
x354
x108

asked: Mar 10 '10 at 11:17 PM

Seen: 3145 times

Last Updated: Mar 11 '10 at 01:38 AM