Place Buildings doesnt work correct

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;
}

Could it be that your raycast is hitting your “preview” object itself, and therefore getting closer and closer to the camera as it moves to that hit point on its own outer edge?

I notice you’re not using any layermask at all for your raycast. It probably makes sense to use a layermask that only hits the surfaces where it is valid to place your object.

1 Like

Yeah that could be it.
I will try that later. Thank you very much for helping me. I struggled for days on this and can’t get the Problem. :slight_smile:
(Still a lot to learn ^^)