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

    TheGreydiant

    Joined:
    Aug 31, 2022
    Posts:
    4
    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

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    8,204
    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

    jmgek

    Joined:
    Dec 9, 2012
    Posts:
    177
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections.Generic;
    3.  
    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>();
    8.  
    9.     void Start()
    10.     {
    11.         // Add the instance ID of this GameObject's collider to the list
    12.         colliderInstanceIDs.Add(GetComponent<Collider>().GetInstanceID());
    13.     }
    14.  
    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. }
    26.  
    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.