I’m currently using room-sized trigger colliders to keep track of which room each NPC and trackable object is in, and each time the scene loads I would like to make an array of all the colliders inside each room. I know you can use OnTriggerEnter/Exit to track movement, but is there a method that immediately returns all objects inside the trigger?
Ancient post here, and maybe it wasn’t always this way, but in Unity 2017 you can use a co-routine to turn a trigger off wait a frame and turn it back on to get all the colliders inside/touching to call OnTriggerEnter. With this you can populate a list of colliders from the OnTriggerEnter event. Here is an example.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Collider_Manager : MonoBehaviour
{
public List<Collider> TriggerList = new List<Collider>();
public LayerMask detectMask;
void Start()
{
GetComponent<BoxCollider>().enabled = false;
StartCoroutine(initializeCollider());
}
IEnumerator initializeCollider()
{
yield return null;
GetComponent<BoxCollider>().enabled = true;
yield return null;
}
void OnTriggerEnter(Collider other)
{
if ((detectMask == (detectMask | (1 << other.gameObject.layer))) && !TriggerList.Contains(other))
{
TriggerList.Add(other);
}
}
void OnTriggerExit(Collider other)
{
if (detectMask == (detectMask | (1 << other.gameObject.layer)))
{
if (TriggerList.Contains(other))
{
TriggerList.Remove(other);
}
}
}
}
OnTriggerStay seems to be exactly what you’re looking for.
Call the method and then use an array as you mentioned.
There’s no method to do that, but if the trigger is cube-shaped you could iterate through the bounding boxes of all the objects and see if they intersect the trigger bounding box.