0

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.

Hossein Rashno
  • 3,073
  • 1
  • 25
  • 49
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • is building in your prefabs folder? Did you add building to your script? – Burak Karasoy Nov 14 '15 at 17:22
  • I said building appears in game view, but transparent gets null as a value instead of reference to the spawned gameobject. Building is in the prefab folder and added to script in inspector. – Konrad Nov 14 '15 at 17:39
  • Problem is that Instantiate don't want to return other type than Object even with casting to GameObject or Transform. – Konrad Nov 14 '15 at 17:40
  • try `GameObject transparent=((Transform) Instantiate(stuff)).gameObject;` – Marc Guiselin Nov 14 '15 at 18:03
  • Everything is OK now? Congratulations! But I think maybe post an answer to tells other that you found the solution is better than edit your question :) – Remi Guan Nov 15 '15 at 06:10

1 Answers1

1

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;

}

Konrad
  • 21,590
  • 4
  • 28
  • 64