C# 如何检查游戏对象是否有统一的组件方法?

C# 如何检查游戏对象是否有统一的组件方法?,c#,generics,unity3d,types,unityscript,C#,Generics,Unity3d,Types,Unityscript,我正在写一个方法来检查游戏对象是否有组件 这是: public static bool HasComponent <T>(this GameObject obj) { return obj.GetComponent<T>() != null; } publicstaticboolhascomponent(这个游戏对象obj) { 返回obj.GetComponent()!=null; } 我是这样使用它的: void Update() { if (I

我正在写一个方法来检查游戏对象是否有组件

这是:

public static bool HasComponent <T>(this GameObject obj)
{
    return obj.GetComponent<T>() != null;
}
publicstaticboolhascomponent(这个游戏对象obj)
{
返回obj.GetComponent()!=null;
}
我是这样使用它的:

void Update()
{

    if (Input.GetKey("w"))
    {
        if (gameObject.HasComponent<Rigidbody>())
        {
            print("Has a rigid body.");
            return;
        }

        print("Does not have rigid body.");
    }
}
public static class ExtensionsHandy
// The wrapper class name is actually irrelevant - it is not used at all.
// Choose any convenient name for the wrapper class.
    {
    
    public static bool HasComponent <T>(this GameObject obj) where T:Component
        {
        return obj.GetComponent<T>() != null;
        }
    
    public static bool IsNear(this float ff, float target)
        {
        float difference = ff-target;
        difference = Mathf.Abs(difference);
        if ( difference < 20f ) return true;
        else return false;
        }
    
    public static float Jiggle(this float ff)
        {
        return ff * UnityEngine.Random.Range(0.9f,1.1f);
        }
    
    public static Color Colored( this float alpha, int r, int g, int b )
        {
        return new Color(
            (float)r / 255f,
            (float)g / 255f,
            (float)b / 255f,
            alpha );
        }
  
    }
void Update()
{
if(Input.GetKey(“w”))
{
if(gameObject.HasComponent())
{
印刷体(“具有刚体”);
返回;
}
打印(“没有刚体”);
}
}
游戏对象没有刚体,但仍在打印它的刚体。

它只是

public static bool HasComponent <T>(this GameObject obj) where T:Component
    {
    return obj.GetComponent<T>() != null;
    }

尝试调试。记录对象名称以确保您没有意外地将此脚本放在另一个对象上,也许?我有,但仍然打印出它有刚体,即使它没有。嗨@HamzaHasan。。。答案是OP在泛型中犯了语法错误。必须在末尾有where子句,否则调用GetComponent()返回的值将是无意义的。。。。它正在返回,我相信它是否有任何组件连接。这只是一个语法错误,Hamza。@JoeBlow Ok,所以它返回一个非空值。也是因为这个吗?嗨,哈姆扎,如果我不清楚的话,对不起。我相信既然“T”基本上是“空白”。。。您正在询问它“GetComponent()”。注意,角括号中没有任何内容。这意味着您要问它是否有任何组件——任何类型的组件。我能解释一下吗?当然,它必须有附加的组件(某种类型!),所以它返回“true”。有道理吗?违约者:P。。类似的用户也存在于gamedev中,比如:DYou打赌我是。谢谢你的帮助,很抱歉没有回来。Unity首先解决了这个问题,所以我再也没有回头看。不过,谢谢!
// Here's an unbelievably useful array handling category for games!

public static T AnyOne<T>(this T[] ra) where T:class
    {
    int k = ra.Length;
    int r = UnityEngine.Random.Range(0,k);
    return ra[r];
    }