Hello everyone! What I’m trying to do is to create an object “Projection” using prefab “Building 1” when player clicks a GUI button and move it around the screen with mouse cursor. And also remove the object when player right-clicks. Everything except changing object position and deleting it works, so I assume the problem is that I do not reference the newly created object properly. Also game generates error report:
“InvalidCastException: Cannot cast from source type to destination type.
ConstructGUI.OnGUI () (at Assets/Scripts/ConstructGUI.cs:42)”
Here is the code itself:
using UnityEngine;
using System.Collections;
public class ConstructGUI : MonoBehaviour {
public int NewBuilding;
private GameObject Projection;
public Transform BuildingPrefab;
void Update () {
if (NewBuilding > 0) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if ((Physics.Raycast(ray, out hit)) && (NewBuilding > 0)) {
Projection.transform.position = hit.point;
}
if (Input.GetMouseButtonDown(1)) RemoveProjection();
}
}
void RemoveProjection () {
if (NewBuilding > 0) Destroy(Projection);
NewBuilding = 0;
}
void OnGUI () {
GUI.Box(new Rect(10,10,120,90), "Construction Menu");
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(GUI.Button(new Rect(30,40,80,20), "Building 1")) {
RemoveProjection();
if (Physics.Raycast(ray, out hit)) {
Projection = (GameObject)Instantiate(BuildingPrefab, hit.point, Quaternion.identity);
NewBuilding = 1;
}
}
if(GUI.Button(new Rect(30,70,80,20), "Building 2")) {
RemoveProjection();
//NewBuilding = 2;
}
}
}