Unity - Convert Collider2D to Collision2D

本文关键字:to Collision2D Collider2D Convert Unity | 更新日期: 2023-09-27 18:02:24

我有两个函数,一个是OnCollisionEnter2D,一个是OnTriggerEnter2D。我需要将Collision2D转换为Collider2D,反之亦然:

//  c# script
void OnCollisionEnter2D(Collision2D collision) {
    foo(collision);
}
void OnTriggerEnter2D(Collider2D collider) {
    foo(collider);
}
void foo(Collision2D coll){
    //checking inside here
}

当然,这不会编译因为我给了foo collider, collider不是Collision2D。我注意到这两种数据类型几乎是相同的。我不能选这两个。有人能帮我转换或建议一个解决方案吗?

提前感谢!!

编辑:

这是我的检查代码…

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
}

Unity - Convert Collider2D to Collision2D

可以使用泛型方法

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")
    {
    }
}

foo()添加一个重载方法:

//  c# script
void OnCollisionEnter2D(Collision2D collision) {
    foo(collision);
}
void OnTriggerEnter2D(Collider2D collider) {
    foo(collider);
}
void foo(Collision2D coll){
    //checking inside here
}

void foo(Collider2D coll){
}