yummypasta yummypasta - 3 months ago 35
C# Question

Unity - Convert Collider2D to Collision2D

I have two functions, one is OnCollisionEnter2D and one is OnTriggerEnter2D. I need to convert Collision2D to Collider2D or vice versa:

// c# script
void OnCollisionEnter2D(Collision2D collision) {
foo(collision);
}

void OnTriggerEnter2D(Collider2D collider) {
foo(collider);
}

void foo(Collision2D coll){
//checking inside here
}


Of course, this isn't going to compile because i am giving foo collider, and collider isn't a Collision2D. I have noticed that these two data types are almost the same. I can't cast these two. Could someone please help me convert or suggest a workaround?

Thanks in advance!!

Edit:

This is my checking code...

int coins;

void Start(){
coins = 0;
}

void foo(Collision2D coll){
if(coll.gameObject.tag == "coin"){
coins++;
}
//this works for both Collision2D and Collider2D because both have the gameObject property

}

Answer

You could use a generic methode

void OnCollisionEnter2D(Collision2D collision)
{
    foo<Collision2D>(collision);
}

void OnTriggerEnter2D(Collider2D collider)
{
    foo<Collider2D>(collider);
}


public void foo<T>(T c)
{
    GameObject g;

    if (typeof(T) == typeof(Collider2D))
    {
        Collider2D obj = (Collider2D)(object)c;
        g = obj.gameObject;
    }
    else {
        Collision2D obj = (Collision2D)(object)c;
        g = obj.gameObject;
    }

    Debug.Log(g.tag);

    if (g.tag == "coin")
    {

    }
}
Comments