Placing Objects Via Raycast Hit Detection in Unity 2021

In this article we’ll cover using the Physics.Raycast system to instantiate game objects when a player clicks on the screen.

Initial Scene Setup
Either create a new scene or a new project with the Input System package installed.
Add a cube and stretch it out to act as a floor for this prototype.

Then create an empty game object and name it “InputManager”.
Create an input script and assign it to the InputManager game object.

Finally, create a sphere prefab and sphere material assigned to this prefab with an easy to identify color.

Let’s Code It
The first thing we’ll need in our PlayerInput script is a reference to the Main Camera game object.

We’ll be able to reference where the player has clicked on the screen only by use of the Main Camera game object.

Once we’ve created our Camera variable we need to assign the Main Camera to it as shown above.

I’ve pulled over the relevant raycast code used in the previous article for changing the color of game objects the player has clicked.

Looking over the exposed methods for RaycastHit on my rayHit variable reveals a method called “point”.

“The impact point in world space where the ray hit the collider.” (Vector3)

With access to that information, it should be straight forward to instantiate my sphere prefab with the vector3 provided here.

Before I’ll be able to instantiate the prefab though, I’ll need to add a variable reference to it and assign it in the Editor.

I’ve added a Debug.Log line to showcase the values being generated and the Instantiate line to accomplish our task.

And there you have it!

What if we don’t like spawning game objects embedded in a floor?
Weird concept, I know, but stick with me for just a bit.

Why not spawn them, *on top* of the floor?

Much better!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store