C# 如何在unity中使用泛型函数?

C# 如何在unity中使用泛型函数?,c#,unity5,generic-programming,C#,Unity5,Generic Programming,我试图确定哪个组件被用作参数,但我不知道如何尝试访问它,因为一切都会引发错误 第一个函数AttemptMove检测光线投射与之碰撞的对象。然后调用OnCantMove函数并使用T作为参数 protected virtual void AttemptMove<T> (int xDir, int yDir) where T: Component { RaycastHit2D hit; bool canMove= Move (xDir, yDir, out hit);

我试图确定哪个组件被用作参数,但我不知道如何尝试访问它,因为一切都会引发错误

第一个函数AttemptMove检测光线投射与之碰撞的对象。然后调用OnCantMove函数并使用T作为参数

protected virtual void AttemptMove<T> (int xDir, int yDir) where T: Component
{
    RaycastHit2D hit; 
    bool canMove= Move (xDir, yDir, out hit);
    if (hit.transform == null)
        return;

    T hitComponent = hit.transform.GetComponent<T> ();
    //Debug.Log (hit.transform.GetComponent<T> ());
    if (!canMove && hitComponent != null)
        OnCantMove (hitComponent); 
}

protected override void OnCantMove<T>(T component)
{       
    Wall hitWall = component as Wall;
    hitWall.DamageWall (wallDamage);
    animator.SetTrigger ("PlayerChop");
}
受保护的虚拟void尝试移动(int-xDir,int-yDir),其中T:Component
{
雷卡斯特2D命中;
bool canMove=移动(xDir、yDir、out hit);
if(hit.transform==null)
返回;
T hitComponent=hit.transform.GetComponent();
//Log(hit.transform.GetComponent());
如果(!canMove&&hitComponent!=null)
OnCantMove(hitComponent);
}
受保护的覆盖无效OnCantMove(T组件)
{       
墙hitWall=作为墙的构件;
hitWall.DamageWall(墙损坏);
animator.SetTrigger(“PlayerChop”);
}

我希望能够像破坏墙壁一样伤害敌人玩家,所以我需要能够在OnCantMove函数中进行某种检查,以确定T是什么。我对unity中的泛型函数非常不熟悉,因此我们将非常感谢您的帮助。

您可以使用

 Type itemType = typeof(T);
 if(itemType == typeof(int) || itemType == typeof(decimal))

错误到底是什么?
Wall-hitWall=组件作为墙为什么?不要使用类似于T:Wall的
protectedoverride void OnCantMove(T组件)
,仔细想想,您有这种方法。。嗯,只是说,将
转换为
可能会返回null,这将很有趣。我尝试检查
组件.transform.tag
将调试什么,但在控制台中没有显示任何内容:错误CS0246:找不到类型或命名空间名称“type”(您是否缺少using指令或程序集引用?)-