Unity/C# Find object and get component

22,046

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

Solution 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");
Share:
22,046
Ghoul Fool
Author by

Ghoul Fool

Ghoul fool is an artist. ...not a programmer He's really lost. #actuallyautistic

Updated on July 09, 2022

Comments

  • Ghoul Fool
    Ghoul Fool over 1 year

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