Hello,
I am new to Unity C# scripting and I tried to make some kind of drag an drop Buildingsystem.
I got some Code that works but there is a Problem I cant fix. The object should spawn where the raycast hits and then moves with the hold mouse to the position of choise on the map. But the object always moves from this point to the camera. I have no idea why this happens. Can someone help me out?
Here ist the Code:
[SerializeField]
private GameObject placeableObjectPrefab;
private GameObject currentPlaceableObject;
public GameObject canvasBuild;
public GameObject canvasOverlay;
private bool buttonClicked = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
private void Update()
{
HandleNewObject();
if (currentPlaceableObject != null)
{
MoveCurrentPlaceableObjectToMouse();
ReleaseIfClicked();
}
}
private void ReleaseIfClicked()
{
if (Input.GetMouseButtonUp(0))
{
currentPlaceableObject = null;
buttonClicked = false;
GameObject.Find(“CameraRig”).gameObject.GetComponent().enabled = true;
canvasBuild.SetActive(true);
}
}
private void MoveCurrentPlaceableObjectToMouse()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
currentPlaceableObject.transform.position = hitInfo.point;
//currentPlaceableObject.transform.rotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
}
}
private void HandleNewObject()
{
if(buttonClicked == true && currentPlaceableObject == null)
{
canvasBuild.SetActive(false);
GameObject.Find(“CameraRig”).gameObject.GetComponent().enabled = false;
currentPlaceableObject = Instantiate(placeableObjectPrefab);
}
else
{
//Destroy(currentPlaceableObject);
}
}
public void PlaceSchmiede()
{
buttonClicked = true;
}