- Home /
How to check what type of Collider has been hit?
I have a CircleCollider2D and a BoxCollider2D on my character and when the character collides with a platform that has a trigger on it I want to check if it was the BoxCollider2D that hit.
I was trying this and getting an error:
void OnTriggerEnter2D(Collider2D col)
{
if (col.GetType() == BoxCollider2D) {
...
Not regarding the answer below (which is totally right and propably better than this), your code will work if you write if(col.GetType() == typeof(BoxCollider2D)) { }
Ahh ok, yeah that was what I was originally trying to do.
Answer by roojerry · Apr 10, 2015 at 08:19 PM
Try is
if (col is BoxCollider2D)
Error: 'The given expression is never of the provided type ('BoxCollider2D')
You're most likely off topic here. You probably work inside OnCollisionEnter2D ins$$anonymous$$d of OnTriggerEnter2D. 2D collision callbacks do not receive a Collider2D but a Collision2D class which contains all sorts of information about the collision. One of that is the collider. Please read the question carefully.
Answer by aminbenslimen9 · Jun 23, 2019 at 12:14 PM
.col.collider.GetType().ToString() == "UnityEngine.BoxCollider2D"
No, just no. First of all you seem to work on a Collision2D object (which you get in the OnCollision callbacks) ins$$anonymous$$d of a Collider2D (which you get in the OnTrigger callbacks) which was asked in the question. Second This is a horrible approach in terms of type safety, error avoidance and performance.
using ToString on the System.Type object of the collider will allocate a new string.
using a hardcoded classname in a string is prone to typos which are not detected by the compiler
using a hardcoded classname will cause issues it Unity decides to change the namespace of the class
Answer by theonlysake · Dec 16, 2019 at 12:44 AM
Actually the best way to do this is:
BoxCollider2D collider = col as BoxCollider2D
If (collider != null) { //Perform Actions Here }