Stick Object to Raycast

Hey
I want that an object is sticked to the raycast I do that it moves along where I watch with my player. I am working on a building System like in Rust and I want that there is a “preview obeject” that you see where you`re going to place the building.

Here is my script for only the placeing:

#pragma strict

var rayLength : int = 10;

var prefabObject: GameObject;

var playerCamera : GameObject;

var player : GameObject;


function Update ()
{
	var hit : RaycastHit;
	var fwd = transform.TransformDirection(Vector3.forward);
	
	
	if(Physics.Raycast(transform.position, fwd , hit, rayLength) && Input.GetKeyDown("f"))
	{	
		hit.point = hit.point + new Vector3(0, 2, 0);
		Instantiate(prefabObject, hit.point, player.transform.rotation); 
	}
}

Hope Someboady can help me thanks!

Instead of instantiating your preview object each frame in Update(), instantiate it once in Start(). Then set it to active using SetActive(true) and inactive using SetActive(false) when your ray cast hits or doesn’t hit.

inside the if statement for the ray cast hitting, simply set the preview object to active and set its position to the hit.point.