- Home /
Getting a List of Gameobjects in a collider
I need a list of game objects that are inside of a boxcollider and be able to access each one individually. there will be hundreds of said game objects so I can't just get all of the objects with a certain tag and compare distance.
Answer by Fariborzzn · Feb 01, 2020 at 12:03 AM
you can use: Physics.OverlapBox It will Find all colliders touching or inside of the given box. so you can set the size of your box for your purpose (you mentioned distance) HERE
Collider[] hitColliders = Physics.OverlapBox(gameObject.transform.position, transform.localScale / 2, Quaternion.identity, m_LayerMask);
and use for or foreach loop to do your function on them
it will return collider so for accessing game object you have to this:
Collider.gameObject
Just in case anybody needs a complete and working code example:
private void GetObjectsInBoxCollider(BoxCollider collider)
{
Collider[] colliders = Physics.OverlapBox(
center:collider.transform.position + (collider.transform.rotation * collider.center),
halfExtents:Vector3.Scale(collider.size * 0.5f, collider.transform.lossyScale),
orientation:collider.transform.rotation,
layerMask:~0);
List<Transform> objectsInBox = new List<Transform>();
foreach (var c in colliders)
{
Transform t = c.transform;
while (t.parent != null && t.GetComponent<SomeType>() == null) t = t.parent;
if (t.GetComponent<SomeType>() != null
&& t != collider.transform
&& !objectsInBox.Contains(t))
objectsInBox.Add(t);
}
for (int i = 0; i < objectsInBox.Count; i++) DoSomething(objectsInBox[i]);
}
Just replace "SomeType" with the type or classname you are looking for and add a method to do whatever you like to do with your gameobjects.