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]

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.

--

--

--

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!

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Automating Azure SQL Database backups using docker

DevOps for Pandemics

Wiley Teams activity January 2020 — September 2020

Create a Personalized Training Experience

9 lessons learned building MVPs

I ❤ systemd: Running a splash screen, shutting down screens and an IoT service with Python on…

CSS Flexbox: flex-wrap

Quiz | Computer Fundamentals | Set 17

Speeding Up the Conversion Between PySpark and Pandas DataFrames

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
Adam Reed

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!

More from Medium

Variables! — The building blocks of programming

Read Between The Lines

Command Interface: Recording input

4 Ways of Playing Animation-Related Sounds in Unity