How to check whether Collider is part of List?

So I have a list of GameObjects contained within a list of ScriptClass. If I had OnTriggerEnter, how would I check if the collider is part of the ScriptClass list?

You probably want your list to be typed to Collider (or Collider2D), and reference all the objects via said colliders. Then when the collision happens, you just iterate through the list and check if it equals (==) any of the colliders in said collection.

Referencing via the GameObject itself is usually not particularly useful. You would have to TryGet/GetComponent on every game object to check if it had a collider otherwise.

3 Likes
using UnityEngine;
using System.Collections.Generic;

public class TriggerEventHandler : MonoBehaviour
{
    // List to store instance IDs of colliders that entered the trigger
    static List<int> colliderInstanceIDs = new List<int>();

    void Start()
    {
        // Add the instance ID of this GameObject's collider to the list
        colliderInstanceIDs.Add(GetComponent<Collider>().GetInstanceID());
    }

    private void OnTriggerEnter(Collider other)
    {
        // Check if the collider's instance ID is in the list
        int colliderInstanceID = other.GetInstanceID();
        if (colliderInstanceIDs.Contains(colliderInstanceID))
        {
            // Collider's instance ID is in the list, do something
            Debug.Log("Collider with instance ID " + colliderInstanceID + " entered the trigger.");
        }
    }
}

I personally use Instance ID’s for this, so you’re not doing a compare.

Switch other to this depending on what instance ID you want to know triggered.