Here Is A Script I made:
using UnityEngine;
using System.Collections;
public class SpawnGui : MonoBehaviour
{
private bool showGUI;
void Start ()
{
showGUI = false;
}
void Update ()
{
if(Input.GetKeyDown(KeyCode.I))
{
if(showGUI == true)
{
showGUI = false;
}
else if(showGUI == false)
{
showGUI = true;
}
}
}
void OnGUI()
{
if(showGUI == true)
{
if(GUI.Button(new Rect(20,20,100,80), "Cube"))
{
}
}
}
}
I want know how to place a Prefab when someone clicks the GUI Cube button at the mouse position.
EXTRA: when I press āIā I want it to disable the Mouse Look script
This will place an object in the scene 20 units from the camera:
public class GoAtPrefab : MonoBehaviour {
public GameObject goPrefab;
void Update () {
if (Input.GetMouseButtonDown (0))
{
Vector3 v3T = Input.mousePosition;
v3T.z = 20;
v3T = Camera.main.ScreenToWorldPoint (v3T);
Instantiate(goPrefab, v3T, Quaternion.identity);
}
}
}
You cant Instantiate a GameObject. You can Instantiate a Transform and make it to a GameObject.
I have modified your code a little bit.
Hope it Helps: (It just Spawn ur object when u hit an other Object.)
using UnityEngine;
using System.Collections;
public class SpawnGui : MonoBehaviour
{
private bool showGUI;
private string selectedObject = "";
public Transform cubePrefab;
public Transform ballPrefab;
void Start ()
{
showGUI = false;
}
void Update ()
{
if(Input.GetKeyDown(KeyCode.I))
{
if(showGUI == true)
{
showGUI = false;
}
else if(showGUI == false)
{
showGUI = true;
}
}
if(selectedObject != "")
{
if(selectedObject=="Cube")
{
if (Input.GetMouseButtonDown (0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
Transform newTransform = Instantiate(cubePrefab, hit.point, Quaternion.identity) as Transform;
GameObject newGameObject = newTransform as GameObject;
newGameObject.name = "Cube";
}
}
}
if(selectedObject=="Ball")
{
if (Input.GetMouseButtonDown (0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
Transform newTransform = Instantiate(ballPrefab, hit.point, Quaternion.identity) as Transform;
GameObject newGameObject = newTransform as GameObject;
newGameObject.name = "Ball";
}
}
}
}
}
void OnGUI()
{
if(showGUI == true)
{
if(GUI.Button(new Rect(20,20,100,80), "Cube"))
{
selectedObject = "Cube";
}
if(GUI.Button(new Rect(20,40,100,80), "Ball"))
{
selectedObject = "Ball";
}
if(GUI.Button(new Rect(20,60,100,80), "None"))
{
selectedObject = "";
}
}
}
}