Saturday, July 8, 2017

List of Collided

As far as I can tell Unity doesn't have a mechanism natively that tells you all the objects that are currently collided (triggered) in your collider.  The most common approach seems to be managing the list on your own using the OnTriggerEnter and OnTriggerExit:

    void OnTriggerEnter(Collider other)
    {
        if (other.tag == "enemy")
        { 
            allCollisions.Add(other.gameObject);
        }
    }

    void OnTriggerExit(Collider other)
    {
        if (other.tag == "enemy")
        {
            allCollisions.Remove(other.gameObject);
        }
    }

One extra point to note, that this approach breaks down if your objects are "exiting" because they are destroyed.  In my case, I wanted to destroy the entire list of objects via an event.  At first I used List.Clear(), however I found that this only nulls all the elements, but doesn't actually clear the elements.  Better was to blow away the list with a new instance.

if (Input.GetButtonDown("Fire1"))
{
   foreach (GameObject enemy in allCollisions)
   {
SeekToKill newBullet = (SeekToKill)Instantiate(bullet, bulletStart.transform.position, bulletStart.transform.rotation);
newBullet.SetTarget(deadbug);
   }

   // clear list including indicies
   allCollisions = new List<GameObject>();
}

No comments:

Post a Comment