I’m trying to make it so as when I click a GUI button an object is instantiated at the mouse’s position AND follows the mouse position around the screen. Unfortunately all it is doing is instantiating the Object at the mouse position at the moment I click on the GUI button and is not following the mouse around.
using UnityEngine;
using System.Collections;
public class SatCamUpdatedGUI : MonoBehaviour
{
RaycastHit hit;
private float raycastLength = 1000;
public Texture HQBtnTex; //Texture for the HQ Button
public GameObject HQPrefab; //Actual HQ prefab
public GameObject FakeHQ; //Mouse Pointer HQ Prefab
private GameObject ChosenPrefab;
void OnGUI()
{
if(GUI.Button(new Rect(26,26,72,72),HQBtnTex))
{
GameObject ChosenPrefab = FakeHQ;
Debug.Log("HQ Chosen");
PlaceHQPrefab();
}
}
public void Update()
{
}
public void PlaceHQPrefab()
{
//ChosenPrefab = Instantiate(Resources.Load("FakeHQ")) as GameObject;
GameObject ChosenPrefab = Instantiate(FakeHQ, hit.point, Quaternion.identity) as GameObject;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if(Physics.Raycast(ray, out hit, raycastLength))
{
Debug.Log(hit.collider.name);
if(hit.collider.name == "Terrain")
{
ChosenPrefab.transform.position = hit.point;
}
}
}
}
I’m basing my script on an earlier script I was using that simply had an object follow the mouse continuously. -
using UnityEngine;
using System.Collections;
public class MousePointer : MonoBehaviour
{
RaycastHit hit;
private float raycastLength = 1000;
void Start()
{
}
void Update()
{
GameObject Target = GameObject.Find("Target");
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if(Physics.Raycast(ray, out hit, raycastLength))
{
Debug.Log(hit.collider.name);
if(hit.collider.name == "Terrain")
{
Target.transform.position = hit.point;
}
}
Debug.DrawRay(ray.origin, ray.direction * raycastLength, Color.yellow);
}
}
I think (please correct me if I’m wrong) that the reason the object doesn’t follow the mouse is that it isn’t using the void Update() and therefor the object position isn’t being updated.
However with the script I’m writing when I use the void Update() function I get objects repeatedly instantiated over and over until the screen is full of them…lol
How do I change it so I get just a single object Instantiated AND that object follows my mouse?
Any suggestions please guys ???