Search code examples
objectunity-game-engineinstantiationgameobject

Unity3D Instantiating as GameObject


My code look like that:

if (Input.GetButtonDown ("Fire2")) {
        GameObject transparent = Instantiate (building, new Vector3 (0, -10,0), Quaternion.identity) as GameObject;
}

Where building is public GameObject which I add through unity Inpsector. After using right click GameObject is instantiated, but transparent variable has null instead of the instantiated GameObject. If I change type of transparent to Object and I remove 'as GameObject' cast, everything works good.

Ok, I find out what was wrong. My building wasn't GameObject, it was Building (class which inherits MonoBehaviour, so have gameobject in itself). Now I instantiate building.gameobject and everything is ok.


Solution

  • It turned out that I initiated 'building' as a Building class (Building is my own class and inherits MonoBehaviour), not as a GameObject so unity had problem to put Building into GameObject. It's looks like that now:

    if (Input.GetButtonDown ("Fire2")) {
        GameObject transparent = Instantiate (building.gameobject, new Vector3 (0, -10,0), Quaternion.identity) as GameObject;
    

    }