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!
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.
Inside the C# script, in the Update function I add the following if statement;
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!