(); ...">

Unity / C # Find an object and get a component

This should be easy:

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

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

Unity errors usually seem useful, but this is just confusing. Cubes are not GameObjects? Any pointers would be appreciated (no pun intended).

+4
source share
2 answers

This is a minor mistake, has been there ... too many times :)

I would explain it this way, given that there is always a chance that I am wrong or misunderstand this problem :)

GameObject - . , GameObject GameObjects , GameObject.

: GameObject GameObjects GameObject. , , GameObject.

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

, Cubey GameObject, Cubey.

, , , , GameObject.

, GameObject myCube Cubey, :

GameObject myCube;

void Start(){
    // Lets say you have a script attached called Cubey.cs
    // This is a slow approach
    myCube = GameObject.FindObjectOfType<Cubey>();
}

// A faster approach is to do
// You need to then attach cubey through the inspector
public GameObject myCube; 

, .

+3

GameObject . A GameObject Component.

GetComponent Find("Cubey")

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

Source: https://habr.com/ru/post/1529029/


All Articles