Unity/C#: Raycast from Mouse Position

Thomas Mauro
4 min readDec 22, 2022

--

Raycasting is a line in 3D space with the ability to detect intersection points. This allows the ray to detect whatever it hits. Things like bullet holes or A.I. cars in racing games use Raytracing. That's how the cars don't hit walls or stay on track for the most part.

To figure out how to get this started and what is needed for this challenge, documentation is a good place to look. After looking into some of the 16 ways to override one thing seemed clear. An if statement and Physics.Raycast was needed. For this demonstration, I will have some cubes in the scene that will change color once the left mouse button is clicked on them.

  • Player.cs made and assigned to the Main Camera
  • Initialize - using UnityEngine.InputSystem
  • Make an if Statement to initialize the Left Mouse Click
  • Define the starting point of the Ray
  • Make a RacaseHit variable and if Statement to get information from what the ray hits
  • Change that code to it will actually read out the information of the actual objects ray will hit
  • Enable access to allow color changing/random color of an object via the Left Mouse Click

Right now the color of every object will randomly change when pressed via the left mouse click. Let's make it so only cubes will change if clicked, Spheres will do nothing and Capsules will turn green.

  • Renamed The Cube back to Cube and added two more cubes
  • Added a sphere and capsule into the scene
  • Placed the objects other are both visible
  • Create a tag called Cube and put that tag on the cubes
  • Now do the same thing with the Sphere and Capsule ( Make their Tags and assign them )
  • Make a switch statement for the hit information and identify the objects ( // who did I hit? )

Now the Cubes colors will randomly change, the Sphere will remain the same and the Capsule will turn green when clicked on.

--

--