Easily check type of collider gotten from OnTriggerEnter2D()

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?

You can use GetType().

void OnTriggerEnter2D(Collider2D other) {
if (other is CircleCollider) {
Debug.Log("It's a circle!");
}
}

One of those “this is so easy I’m pretty sure StarManta is trolling me” syntaxes. But yep.

1 Like

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.