Unity Interaction — Placing Objects Via Raycast Hits

Sean Duggan
2 min readMay 1, 2024

--

So, let’s try something a little different. Instead of changing an existing object, let’s create a new one. Specifically, we’ll instantiate a sphere on the surface of whatever we click upon, with the scene starting with a plane.

First step, we’ll create a prefab sphere to be placed. I created a radius 5 sphere with a free jelly texture.

Our sphere instantiation class is simple. We do the same Update() as before, but if there’s a ray cast hit, we look at the point on the hit, and we instantiate our sphere there.

public class InstantiateSphere : MonoBehaviour
{
[SerializeField] GameObject _prefab;

// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

RaycastHit hitData;
if (Physics.Raycast(ray, out hitData, 1000))
{
Vector3 hitLocation = hitData.point;
Instantiate(_prefab, hitLocation + Vector3.up * 0.5f, Quaternion.identity);
}
}
}
}

And, does it work? I’d argue yes.

--

--