【问题标题】:Unity/C# Find object and get componentUnity/C# 查找对象并获取组件
【发布时间】:2014-02-26 17:29:48
【问题描述】:

这应该很容易:

GameObject myCube = GameObject.Find("Cubey").GetComponent<GameObject>();

刚刚出现错误 CS0309:类型 UnityEngine.GameObject 必须可转换为 UnityEngine.Component 才能将其用作泛型类型或方法 UnityEngine.GameObject.GetComponent() 中的参数 T

通常 Unity 显示的错误很有用,但这只是令人困惑。立方体不是游戏对象吗?任何指针都将不胜感激(没有双关语)。

【问题讨论】:

  • 可能组件不是GameObjects - 您正在尝试将GetComponent&lt;T&gt; 的值分配给GameObject - 当然您想要GameComponentComponent(或其他Unity 中的等价物)

标签: c# unity3d gameobject


【解决方案1】:

GameObject 不是一个组件。 GameObject 附有一堆 Components。

您可以取消GetComponent 调用,只使用Find("Cubey") 的结果

GameObject myCube = GameObject.Find("Cubey");

【讨论】:

    【解决方案2】:

    一个简单的错误,去过那里......实际上太多次了:)

    我会这样解释:

    GameObject 是一种类型。 GameObject 类型只能与 GameObjects 或继承自 GameObject 的事物相关联。

    这里的意思是:GameObject变量只能指向GameObjects和GameObject的子类。下面的代码指向一个 type GameObject 的组件。

    GameObject.Find("Cubey").GetComponent<GameObject>();
    

    代码显示“找到 Cubey 并指向附加到 Cubey 的 GameObject”。

    我猜如上所述,您要查找的组件不是 GameObject 类型。

    如果您希望变量 GameObject myCube 指向 Cubey,您可以这样做:

    GameObject myCube;
    
    void Start(){
        // Lets say you have a script attached called Cubey.cs, this solution takes a bit of time to compute. 
        myCube = GameObject.FindObjectOfType<Cubey>();
    }
    
    // This is a usually a better approach, You need to attach cubey through the inspector for this to work.
    public GameObject myCube; 
    

    希望对遇到同样问题的人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      • 2013-01-25
      相关资源
      最近更新 更多