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.

[Side Note]

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 collison will be stored in the RaycastHit variable “hitInfo”. The coordinates will then be displayed in the console log.

Hi, my name is Adam Reed and I am a software engineer specializing in Unity and C# development. Feel free to scroll through and check out some of my work!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store