Placing Objects via Raycast Hits in Unity
Objective: To Instantiate a sphere game object where we click the mouse using raycasting in Unity.
Moving on from the last article where we got our raycast setup, let’s now instantiate a game object where we click on the screen.
Keeping with the super simple project setup theme, I am just creating a 3D Plane game object and flipping it on it’s side, creating a dark material so we can see when we add a white game object.
Existing Code to Modify
Here we have our existing code from that last article that we are going to build our additional logic into:
Let’s create a Serialized ‘_spherePrefab’ field so that we can drag and drop a sphere prefab into this field in the Inspector in Unity.
In order to keep our Hierarchy clean from all the instantiated game objects, let’s create a container that will hold them all — ‘_sphereContainer’. Now, I need to create an empty game object (making sure to zero out he transforms — 0, 0, 0) in Unity and name it ‘Sphere_Container’. We will then set the parent of the instantiated game objects to this.
We no longer have a need for the MeshRenderer as we aren’t adjusting any colors, so we can remove this.
The most important aspect for this is that we are going to be using ‘hitInfo.point’ to tell Unity where we want the instantiated sphere to be placed (where we click the mouse, as long is it is on the plane). This is the impact point where the raycast collides with the Plane.
Physics Raycast — Unity Documentation
RayCastHit — Unity Documentation
RayCastHit.point — Unity Documentation
Ray — Unity Documentation
Debug.Drawline — Unity Documentation
Polling Actions — Unity Documentation
ReadValue<> — Unity Documentation
Casting Raycasts from Mouse Position in Unity
“Raycasting With Layer Masks in Unity”