How To Use Raycasting To Detect Collisions In Unity With C#

Adam Reed
1 min readMay 30, 2021

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]

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.

--

--

Adam Reed

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!