- Home /
Find objects overlapping a collider
Hi,
I'm trying to find all the gameobjects that are within range of the current collider. I don't want to use event-handling methods like OnTriggerXXX/OnCollisionXXX, and I don't want any of the objects to have rigidbodies either. All I want is given a collider, find all the other colliders that overlap it.
The closest thing I know of is Physics.OverlapSphere, but it's limited to a sphere shape. I'd like to do something very similar with a collider.
Any ideas?
Well you know the size of the object and it's position. You could check if two objects are within' eachothers size area and position. Though, may I ask, why don't you want to use rigidbodies or colliders or OnCollision/Trigger?
@jacobschellenberg - adding rigidbodies hinders performance (specially when there are many of those objects), and using OnCollision/Trigger when you simply want to check something is somewhat of a headache... Take for example spawning objects in random locations, or generating objects in a random map. Once you spawn the object, you want to check that it doesn't overlap another object. Using OnCollision, you will have to wait for the next frame, relocate the object, and then wait for the next frame to check again... Also, it doesn't work without rigidbodies.
@meat5000 - that seems like a good solution, except that I'd have to check it against all the gameobjects, which might cause some performance issues. Any ideas how to avoid those?
You could do the Physics.OverlapSphere() first, then do the Bounds.Intersect() for anything it finds. It is probable that under the hood, Unity is iterating through all the colliders with OverlapSphere(), so it might not buy you anything. That is, if you do a distance check in your loop before you do the Bounds.Intersect() you may have similar performance.
If you have 1000s or 10,000s of smaller, non-moving object, there there are data structures that can make the detection more efficient, but it would be a bunch of work that likely would not make much difference for a smaller number of objects. For example you might make use of an Octree-like data structure.
Answer by meat5000 · Nov 13, 2013 at 04:14 PM
http://docs.unity3d.com/Documentation/ScriptReference/Bounds.Intersects.html
Something like this?
Although if you used OverlapSphere you could put in a layermask. This function actually checks against bounding volumes, not colliders.
I haven't really played with changing the size of a bounding volume. You could supposedly have an empty object and set its bounding volume to any size you choose, using intersect to find a crossing.
What's the difference between bounding volume (collider.bounds) and a collider, in terms of intersection?
This means it only works if you want to check in a box shape that is rotated to be aligned with the world axis, otherwise you'll get less-predictable behaviour.