Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Question 2 colliders on 1 object, detect which ran OnTriggerEnter2D?

Discussion in 'Scripting' started by Juice-Tin, Mar 13, 2023.

  1. Juice-Tin

    Juice-Tin

    Joined:
    Jul 22, 2012
    Posts:
    233
    Hi, I have the following setup for characters in my shooter game:
    - Circle collider (head)
    - Capsule collider (body)


    Everything's been going well for detecting body/headshots. However I just noticed that both colliders are triggering OnTriggerEnter2D and OnTriggerExit2D when entering trigger zones. This is problematic as you could walk in a zone, but then when looking around your head is constantly exiting/entering.

    Is there a way to either disable the CircleCollider2D (head) from overlapping these zones, or detect which one ran the OnTriggerEnter2D function so I may ignore it if it's the head?

    Thanks!
     
  2. Sluggy

    Sluggy

    Joined:
    Nov 27, 2012
    Posts:
    841
    You could trying using Physics2D.IgnoreCollision to filter out certain objects. Personally, I'd add a third collider on another child gameobejct with a different layer specifically for these kinds of trigger zones.
     
  3. Juice-Tin

    Juice-Tin

    Joined:
    Jul 22, 2012
    Posts:
    233
    Thanks! I actually also found that code right after posting lol :eek:

    Here's how I used it for anyone else wondering:

    Code (CSharp):
    1. Head = Unit.GetComponent<CircleCollider2D>();
    2. Collider2D[] colliders = GameObject.FindObjectsOfType<Collider2D>();
    3.  
    4. for(int i=0; i<colliders.Length; i++){
    5.     if(colliders[i].GetComponent<TriggerZone>()){
    6.         Physics2D.IgnoreCollision(Head, colliders[i]);
    7.     }
    8. }
     
    Sluggy likes this.