Raycasting in Unity Part 2: Foundations

This is the second post in a three part series on Raycasting in Unity. The other posts are:

Find the code on GitHub


Raycasting is a question: “Given this ray casting out into the scene, does it hit anything?” You can also ask “If so, what has it hit?” There are three general components of a raycasting query:

  1. The ray that you want to cast
  2. The question “Does this ray hit anything? If so, what?”
  3. Doing something with the thing you hit.

An important thing to know is that raycasts are Physics based, which means they interact with physics colliders and not meshes in your scene.

1. Constructing the ray

Building a ray is simple enough

Ray ray = new Ray([position], [direction]);

We also need to create an empty ‘Hit’ object to store the data that we get (i.e. the answer to question 3, “What does it hit?”)

RaycastHit hit;

2. Finding out what the ray hit

Asking the question, or firing the raycast, is an if statement:

if(Physics.Raycast(ray, out hit, maxDistance){
    //Handle successful hit here

The idea of an out parameter may be a new concept to you. In short, the Physics.Raycast function can only return one thing (a boolean) but you might want more information from it (such as what object the ray hit). The out keyword flags ‘hit’ as a parameter that may be modified by the Physics.Raycast function, so when you handle a successful hit you can use the freshly modified hit variable

maxDistance is, surprisingly, the maximum distance that the ray will travel. Beyond this distance, the ray ends and will not detect anything further.

3. Do something with the hit

Upon a successful hit, you’ll likely want to do something! In our case we will log out some information about what we hit, and also draw a green line on screen:

if(Physics.Raycast(ray, out hit, maxDistance))
            //Access the object we hit by calling hit.collider.gameObject:
            string hitName = hit.collider.gameObject.name;

            Debug.Log("Successful hit: " + hitName);

            //Draw a green line from position to hit point:
            Debug.DrawLine(transform.position, hit.point, Color.green);

Further Resources

Should you wish to delve further into raycasting techniques, the Unity documentation is a good resource:


If you’re simply following this guide, head onwards to Applications of Raycasting!