Unity/C# Find object and get component

Ghoul Fool picture Ghoul Fool · Feb 26, 2014 · Viewed 20.7k times · Source

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

Answer

Zach Thacker picture Zach Thacker · Feb 26, 2014

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