Casting Raycasts from Mouse Position in Unity

Chris Hilton
3 min readJan 16, 2023


Objective: Cast a ray to a mouse position in Unity, hitting an object and changing it to a random color.

New year, and a new project! This short series is going to look at raycasting, instantiating objects when a raycast collides with an object, layer masks, creating bullet holes and of course point to click movement! I will be using the New Input System where possible.

This article is going to look at covering the basics of getting your raycasts working. Then we will change the sphere to a random color when the ray collides with it.

Fixing Some Simple Errors With the New Input System

If you are going to use the New Input System, make sure to have the package downloaded and installed to prevent getting a namespace error when attempting to access the library:

Further to this, if you are still receiving the error after restarting your IDE and Unity, make sure you have this boxed ticked in Unity:

Edit → Preferences → External Tools → “Generate .csproj files for” → Registry Packages

Getting Setup

This is a really super simple project setup. It has one sphere and an “InputManagerscript attached to the Main Camera game object as this is going to be the origin for our raycasts.

Building Code Logic

To get started we are going to check whether the left button on the Mouse wasPressedThisFrame’.

Then, we are going to store the coordinates of the clicked position using ReadValue() and a Vector2.

Next, let’s store the ray’s origin position where we will always be shooting it from.

Now, when the ray collides with an object, we want it to provide some information for us, so let’s create a variable of type RayCastHit that will store this info — ‘hitInfo’.

Okay, it is time to cast the ray using Physics.Raycast. We are going to provide it with a couple parameters — The origin from where the ray starts and the variable we want to store the collision information in.

For debugging purposes and to give our project a visual confirmation aspect, let’s add a Debug.Drawline and provide some more parameters Ray origin, impact point (hitInfo.point) of the collision and let’s make it green!

Further to this, we are then going to create a variable called ‘hitObject’ of type MeshRenderer, so we can store this type of information to be able to make some changes to the game object, e.g. Change to a random color.

Of course, let’s always null check before we attempt to perform the operation.

Voila!! Click Away…

In the next article, we will take this a step further and start to add game objects where the raycast hits.

Next Article
“Placing Objects via Raycast Hits in Unity”