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

Easily check type of collider gotten from OnTriggerEnter2D()

Discussion in 'Scripting' started by RiokuTheSlayer, Dec 23, 2015.

  1. RiokuTheSlayer

    RiokuTheSlayer

    Joined:
    Aug 22, 2013
    Posts:
    356
    Title!

    I was wondering the easiest way to check the kind of collider you get from OnTriggerEnter. It only returns a Collider2D, which all the collider classes inherit. I have different cases I need to happen for each kind of collider, box, sphere, and poly.

    The way I'd do it right now is using GetComponent<(collider type I'm checking, eg BoxCollider2D)> and seeing if that is null.

    Any better way to do this?
     
  2. Thomas-Mountainborn

    Thomas-Mountainborn

    Joined:
    Jun 11, 2015
    Posts:
    489
  3. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,744
    Code (csharp):
    1. void OnTriggerEnter2D(Collider2D other) {
    2. if (other is CircleCollider) {
    3. Debug.Log("It's a circle!");
    4. }
    5. }
    One of those "this is so easy I'm pretty sure StarManta is trolling me" syntaxes. But yep.
     
    Kiwasi likes this.
  4. RiokuTheSlayer

    RiokuTheSlayer

    Joined:
    Aug 22, 2013
    Posts:
    356
    That worked! I thought it was a pretty core mechanic of a programming language, so I knew there had to be a simple way to do it.