Al Heck

How to create a Raycast using ScreenPointToRay

First, let’s set our objects up in scene. 4 different objects with 4 different names.

Next, we want to check if we press the left mouse button.

Now to do a raycast like this, we need to set this script on our main camera and determine our origin. Our origin needs 2 things — the object which we are casting from and how we are casting it. In this case, we are casting from the camera and we are using the mouse input to cast.

We then need a output or what we hit. We generally call this the hitInfo.

Now we need to do a check and see what we hit. We do this using physics.raycast and check 2 parameters, our origin and what we hit. We can also run distance checks as well.

Then we can see what we hit and do checks based on it’s name, if it has a collider, or any other number of variables.

Unity Developer and Software Engineer who loves making games with GameDevHQ