Casting Raycast from Mouse Position in Unity

Tyler Smallwood
3 min readMay 5, 2023

Objective: Use Raycast to change color of objects.

In this article we will use the New Input System to get the mouse position and on left mouse button, check to see if we hit something and if we do change it’s color. Then we will clean it up to check for what we are hitting and have a different effect. To start off we need a Cube in the scene.

Next create a script and attach it to and Empty object.

Inside this script we will need to grab the New Input System Library.

Next we will check for the left mouse button click. We will need to use Mouse.current.LeftButton.wasPressedThisFrame.

Once we get an Input from the mouse we will create a local RaycastHit variable, get the mouse position by creating another local variable and assigning it to the mouse Position.ReadValue();. Next is to create a Ray by using Camera.Main.ScreenPointToRay(). ScreenPointToRay will get the location of the mouse and translate the position based on the screen.

We will assign the mousePosition into the ScreenPointToRay.

Now we need to check to see if our Raycast hit anything. For this we use Physics.Raycast(vector3 position, out Raycast) in an If statement.

To change the material color, we can create another local variable and assign it to the hit objects meshrenderer. When the Raycast hits an object it’ll return information under the hit variable. Next we can do a quick null check, if it is null return.

Now all we have to do is assign the hitRender.material.color to Random.ColorHSV(); This will turn the object a random color.

If we want to, we can decide what happens if it hits an object other than a cube. To do this we will need to start with creating a few different tags.

Now assign them to the respective object.

Back in the script, all we have to do is use a switch statement and change color to how we want. For this example, cube will turn a random color, Capsule will turn black and sphere, nothering will happen.

This is one use of using raycast. Thank you for reading and have a wonderful day!

--

--

Tyler Smallwood

I am passonate on learning to program and use Unity to become a skillful Unity Developer