Shooting with raycast in Unity

in shooting games usually, a real bullet is never instanced in the scene, very often what we see is a particle effect. The magic behind a headshot is usually about raycast and colliders that are hit.

A raycast is a ray that starts from a point of origin and identifies the first object it collides with. We can imagine it as the red laser that is used to play with cats.

Basically, a raycast is composed of an origin point and a direction, to this we can add the maximum distance we want it to reach and a layer mask if we want some particular objects to be ignored.

RaycastHit is a structure we use to store our raycast data. It has a set of properties that are very useful that I leave at this link.

In my TPS example, I want the color of the cubes that I hit with my raycast to be red.

My ray in this case will not start from a gun but from the center of the main camera.

to do this I have declared a variable of type ray that takes as initial position the center of my main camera.
When the ray touches a collider of another game object this is assigned to the variable type RaycastHit, and thanks to its properties we can access for example its position with the point command, or call the components that we can use as in my case the mesh renderer to change its color.

project manager by day, unity developer by night