Unity / C#查找对象并获取组件
这应该很简单:
GameObject myCube = GameObject.Find("Cubey").GetComponent();
只需启动错误CS0309:类型UnityEngine.GameObject必须可转换为UnityEngine.Component,以便将其用作generics类型或方法中的参数T UnityEngine.GameObject.GetComponent()
通常,Unity显示的错误很有用,但这只是令人困惑。 多维数据集不是GameObjects吗? 任何指针都将被赞赏(没有双关语意)。
一个简单的错误,一直在那里..实际上太多次了:)
我会这样解释:
GameObject是一种类型。 GameObject类型只能与GameObjects或从GameObjectinheritance的东西相关联。
这意味着:GameObject变量只能指向GameObjects和GameObject的子类。 下面的代码指向一个GameObject 类型的Component。
GameObject.Find("Cubey").GetComponent();
代码说“Find 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(); } // This is a usually a better approach, You need to attach cubey through the inspector for this to work. public GameObject myCube;
希望能帮助任何人来到这个post同样的问题。
GameObject
不是一个组件。 GameObject
附加了一堆Component
。
您可以取消GetComponent
调用,只使用Find("Cubey")
GameObject myCube = GameObject.Find("Cubey");