Proper way to select/cast collider2D as type

In short, I have collisions with triggers and want to call code depending on what type of collider is involved. I need to select the type of the collider, and then cast that…

            if (cols[0].GetType() == typeof(PolygonCollider2D)) {
                PolygonCollider2D polycolly = cols[0] as PolygonCollider2D;
                PolyIntersect(polycolly);
            }

Is this code the proper way? Or is there a better casting method?

Found solution. C# can cast within a Switch

https://stackoverflow.com/questions/298976/is-there-a-better-alternative-than-this-to-switch-on-type

Collider2D col;

       switch (col) {
           case PolygonCollider2D p:
               PolyIntersect(p, start, end);
               break;
           case CircleCollider2D c:
               CircleIntersect(c, start, end);
               break;
       }

For future reference, you can also use the is keyword:

Collider2D col;

if(col is PolygonCollider2D pollyCol)
{
  // Do something with "pollyCol".
}
1 Like

Okay, although I’d still have to cast it if I want to access PolygonCollider2D members.

Nope! The “pollyCol” variable in the above example is already the casted type.

1 Like

It’s recast within the ‘if’ from its definition. Cool.

1 Like