- Home /
How to add objects to a scene via button click
I'd like to know how to use a button click to bring objects to the scene. Should I create the objects in a separate scene, say scene 1? Create a button in scene 2 and then when the button is clicked the object/s appear.
Answer by mirkobon · Sep 16, 2013 at 08:18 PM
Make a prefab, to do this drag the object in your hierachy to your assets. And as scripting:
var object1 : prefab
var myposition : GameObject;
function OnGUI ()
{
if (GUI.Button(Rect(10,10,100,100),"Button name"))
{
Instantiate(object1, myposition.transform.position, myposition.transform.rotation)
}
}
And in the inspector assing the variables
Thanks $$anonymous$$irkobon! I'd just been looking at the tutorials on youtube for prefabs but they were more to do with spawning objects for shooter games etc. I'll try this out.
theres an error on var object1 : prefab var myposition : GameObject;
there's an error on
var object1 : prefab var myposition : GameObject;
need help!
Add a semicolon to the end of the prefab declaration. $$anonymous$$G. var object1 : prefab;
Answer by dannyskim · Sep 16, 2013 at 08:09 PM
Technically, you could do that I guess... But what you're really wanting is to Instantiate an object:
http://docs.unity3d.com/Documentation/ScriptReference/Object.Instantiate.html
Your answer
![](https://koobas.hobune.stream/wayback/20220613114307im_/https://answers.unity.com/themes/thub/images/avi.jpg)