Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question How to check whether Collider is part of List?

Discussion in 'Scripting' started by TheGreydiant, Apr 4, 2024.

  1. TheGreydiant


    Aug 31, 2022
    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?
  2. spiney199


    Feb 11, 2021
    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.
    Bunny83, TheGreydiant and Ryiah like this.
  3. jmgek


    Dec 9, 2012
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections.Generic;
    4. public class TriggerEventHandler : MonoBehaviour
    5. {
    6.     // List to store instance IDs of colliders that entered the trigger
    7.     static List<int> colliderInstanceIDs = new List<int>();
    9.     void Start()
    10.     {
    11.         // Add the instance ID of this GameObject's collider to the list
    12.         colliderInstanceIDs.Add(GetComponent<Collider>().GetInstanceID());
    13.     }
    15.     private void OnTriggerEnter(Collider other)
    16.     {
    17.         // Check if the collider's instance ID is in the list
    18.         int colliderInstanceID = other.GetInstanceID();
    19.         if (colliderInstanceIDs.Contains(colliderInstanceID))
    20.         {
    21.             // Collider's instance ID is in the list, do something
    22.             Debug.Log("Collider with instance ID " + colliderInstanceID + " entered the trigger.");
    23.         }
    24.     }
    25. }
    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.