How To Use Raycasting To Detect Collisions In Unity With C#
A “Raycast” is a 3D line that is drawn from a point of origin through a target direction and detects any intersecting collisions.
Raycasting has two parts. There is the “Ray Origin” which is the starting point of the ray, and there is the “Raycast Hit” which is an info variable that stores the object that was hit and allows you to call on that object's transform similar to OnCollisionEnter.
Since you can access the objects transform, that means that you can pretty much access any component or script from that object through a raycast as well!
The script below dictates that when you click the left-mouse button down a “Ray” titled “rayOrigin” will be drawn from the “Main Camera’s” position through the position clicked by the mouse. Any collisions will be detected and the (X, Y, and Z) coordinates of the collision will be stored in the RaycastHit variable “hitInfo”. The coordinates will then be displayed in the console log.