Unity/C# Find object and get component

强颜欢笑 提交于 2019-12-10 16:01:42

问题


This should be an easy one:

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

just kicks up error CS0309: The type UnityEngine.GameObject must be convertible to UnityEngine.Component in order to use it as parameter T in the generic type or method UnityEngine.GameObject.GetComponent()

Normally the errors Unity displays are useful, but this is just confusing. Are cubes not GameObjects? Any pointers would be appreciated (no pun intended).


回答1:


An easy mistake, been there.. too many times actually :)

I would explain it like this:

GameObject is a type. The type GameObject can only be associated with GameObjects or things that inherits from GameObject.

The meaning of this is: The GameObject variable can only point to GameObjects and subclasses of the GameObject. The code down below is pointing to a Component which is of type GameObject.

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

The code says "Find Cubey and point to a GameObject attached to Cubey".

I guess as already said above that the Component You are looking for is not of the type GameObject.

If you would like the variable GameObject myCube to point to Cubey you could do:

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; 

Hope that helps anyone coming to this post with the same problem.




回答2:


GameObject is not a component. A GameObject has a bunch of Components attached to it.

You can take away the GetComponent call and just use the result of your Find("Cubey")

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


来源:https://stackoverflow.com/questions/22048835/unity-c-find-object-and-get-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!