Unity : Raycast (Part I)

Matteo Lo Piccolo
4 min readJan 7, 2022

Today we talk about Raycast.
Starting with a simple question : what is a Raycast?

Here we have the reference
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html

Raycasting is incredible useful, and understand when and how use it, can be open our possibility to implement it in many mechanics of our games.

Unlike the 95% of documentation, the Raycast documentation is not “so great” but anyway, let’s create a simple scene in Unity and make some test to clarify as many things possible.

In this scene I have a Cube at 0, 0, 0 and Player script attached to Main Camera.
Super easy.

The purpose of this test is this :
we click an object, in this case the cube, and we change its color to red (or whatever you want)

Break the problem in to small pieces with pseudocode :

Now, in the documentation what we really need to know is this.

After reading this part, we now know that we need an origin point, hence a starting point for the Raycast, a direction and a maximum distant.

Other really important thing, and we can see in this example, is the first variable

RaycastHit hit;

In this variable we store information of object we hit.

If this can be help you, is the same logic when we use
OnTriggerEnter or OnCollisionEnter

Inside “other” and “collision” we store the information of object we collide (or trigger).

Ok, let’s back to Unity.
I continue to use new Input System, so at the top :
using UnityEngine.InputSystem

And we test if we press the left mouse button.

Play it

Mouse Input works.

Now, how can we fire a Raycast from the Camera?
We need to search it, because we can’t know everything, so we research.

If we Google “How can Raycast from Camera in Unity”

This is the first result.
And this is a documentation, so we open it
Here’s a link
https://docs.unity3d.com/Manual/CameraRays.html

This is what we need to know.

And we use this example in our project to test it.

Now, we have an error, and this can be an interesting thing.
If we over the mouse on error

We can’t convert “Vector2Control” to “Vector3”
Now, if store it into a variable like this

We see that this is not a Vector2, but Vector2Control.
To convert this value into Vector3, we need to add this piece of information at the end of Mouse.current.position

Now this is a Vector2 variable

We back to Raycast syntax, and we use the first info we find in the documentation

If we test it

When we left click on the Cube, in the Console we can read “Hit something”.

In the next article we finish this little test with Raycast!

--

--

Matteo Lo Piccolo

Always in love with programming, even if late (I'm already 39 years old) I decided to follow my dream! We will see how far my passion will take me!