Drawing Lines — Raycasting in Unity

Jack Leavey
2 min readJul 28, 2022

--

Raycasting is a common concept utilized in almost every single game you have ever played. Simply put, Raycasts are invisible lines drawn from one point to another, checking for collisions. This is used for point-and-click mechanics, shooting, movement, and other gameplay elements!

Using a raycast to change colors on a cube.

A frequently utilized raycast is a simple one from the mouse, specifically left click. First person shooters utilize this tactic for tracking bullets and checking to see what the projectile hit!

Setting up this raycast is very simple and the chassis can be retuned for a multiple of purposes.

NOTE: The new Unity Input System is being used in this example.

I created a new C# script and attached it to the main camera (as this is where the raycast will be originating from.

In the scene view, I added a 3d cube so I had something to interact with.

This is what we will change using Raycasting.

Inside the C# script, in the Update function I add the following if statement;

This is all the logic needed to use the raycast (and change the color of the object it collides with).

When we press left click, we store the mouse’s position (mousePos), then use that value to create the ray (rayOrigin). We also create a local variable to store the hit info (hitinfo).

Lines 24–30 says that if the raycast collides with something, access the mesh renderer and then change it to a random color!

We can change those final 6 lines to do other things as well. We could call a function to do damage to a target, or destroy the target outright. We could tell a target to move to the clicked location (assuming we have baked a navigation mesh). The raycast itself is just a vessel for game logic to be implemented!

--

--

Jack Leavey

I am a software engineer with years of experience branching into game development, specifically in Unity. Follow along for guides on creating game mechanics!