Ghoul Fool
Ghoul Fool

Reputation: 6937

Unity/C# Find object and get component

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).

Upvotes: 4

Views: 28770

Answers (2)

Viking jonsson
Viking jonsson

Reputation: 489

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.

Upvotes: 3

Zach Thacker
Zach Thacker

Reputation: 2608

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");

Upvotes: 9

Related Questions