Unity How to create buildings on mouse click
In this example two buttons are created. On a mouse click the prefab is created.
- GUIManager.cs
using UnityEngine; using System.Collections; public class GUIManager : MonoBehaviour { private string building; /* TODO: Check if clicked on existing object */ void Update () { // left mouse clicked but not on GUI if (Input.GetMouseButtonDown(0) && GUIUtility.hotControl == 0) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); switch (building) { case "Base": Instantiate(Resources.Load("Base"), ray.GetPoint(10), Quaternion.identity); break; case "Barracks": Instantiate(Resources.Load("Barracks"), ray.GetPoint(10), Quaternion.identity); break; default: break; // build nothing } } } void OnGUI () { if (GUI.Button (new Rect (10, 10, 150, 50), "Build a HQ") ) { building = "Base"; } if (GUI.Button (new Rect (160, 10, 150, 50), "Build a Barracks") ) { building = "Barracks"; } } }