How can I make this move in 3d space?[BUILDING SYSTEM]

I’m trying to make a building system ,but I have no idea where to go with it or how to begin. I want it so that you can move a object that you instantiate and it’s distance from the camera will always be the distance between the camera and this empty gameobject(z axis distance) I have. And it should follow your mouse position when it comes to x and y coordinates ,but when you move your mouse in front of a gameobject that intercepts that distance than it will move in front of that. I’m trying to gain something like Kerbal Space Program’s way of building. Any tips or tutorials you can point me to?

It’s not as hard as you think.

The following code should go into your Update() method. It does exactly what you ask for.

Make sure the object you’ve instantiated is on the Ignore Raycast layer! If you don’t, it’ll come flying towards the camera.

Your next question will probably be “how can I get objects to snap to the right place?”. Well that’s another question, but the easiest way to do it is to create “snap points” on objects, and then add some logic that lets them figure out if they’re near an already-placed snap point :-).

//The distance the object should be from the camera if it's not "in front" of anything
float defaultDistance = 5;

//Make a raycast from the mouse position
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;

Vector3 pos;

//If the ray hits something, get the position of the hit
if (Physics.Raycast(ray, out hit, defaultDistance)){
	pos = hit.point;

	//If it doesn't hit anything, the Ray object will let you get the point it would have hit at a specified distance
	pos = ray.GetPoint(defaultDistance);


//Set the position
transform.position = pos;