- Home /
How do I spawn an object when a button is touched? 2D game
Hi,I'm a newbie to Unity and scripting. Looking through other questions I have a general idea about how to spawn an object when you touch a mobile screen. However, I am not completely sure about how to spawn when a gui button is touched. I've already looked through the Input.GetTouch documentation. I'm also trying to spawn the object into a 2d game
Can anyone provide some basic javascript that could instantiate an object when a gui button is tapped? Where the object is spawned could just be any fixed position thats visible. Does spawning differ in 2d games?
( In Unity 2D games are 3D games but "flatten" by the Camera, so there are no difference between 2D and 3D ) $$anonymous$$y way to do that is to have a collider on the GUI buttons. I then raycast from where the player touch the screen to see if it touch something in the scene. Based on the Class/Object name I then do a specific action.
Answer by FirePlantGames · Jan 03, 2014 at 05:19 PM
var spawnPosition : Transform;
var object : GameObject;
funtion OnGUI()
{
//create a button
if (GUI.Button(Rect(10,10,200,20),"Spawn"))
Instantiate(object,spawnPosition.position,spawnPosition.rotation);
// ^^ Instantiate the object
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613125436im_/https://answers.unity.com/themes/thub/images/avi.jpg)