Raycast In Unity || All About Raycast

Share on social media

In this article, we will understand what is Raycast in unity and how to use them in different use cases. So let’s begin.

What is raycast in unity?

Raycast in unity is like a laser beam, which starts from its origin, moves ahead in its specified direction, and goes to its max distance. Raycast will return true if it gets hit with any object else false. It is very useful for detecting objects.

There are many use cases of raycast like we can create bullet shooting with it, it can get any information of the gameobject and check if the player is grounded or not. So there are many things that we can do with the raycast.

Many newcomers struggle with the raycast to make it work. If you are also a beginner so don’t worry we will understand raycast step by step and also different use cases of raycast in unity which is useful for you. So let’s start.

Basic Of Raycast In Unity

So let’s understand the basics of raycast in unity. So here are the variable and functions that we want to understand.

  • Ray
  • RaycastHit
  • Physics.Raycast()

Ray:-

A ray is an infinite line starting at the origin and going in some direction.

A ray contains the details of a ray i.e. origin point and direction. It represents in a struct data format.

RaycastHit:-

Structure used to get information back from a raycast.

When a ray hits any gameobject at that point RaycastHit contains the data of that gameobject. It allows us to use that data to perform any action we want.

Physics.Raycast() :-

Casts a ray, from point origin, in direction, of length maxDistance, against all colliders in the Scene.

It is the function that casts the ray in unity.

How To Create A Ray In Unity

Let’s create a basic raycast function to detect and destroy the gameobject.

To create a raycast in unity, First, we will create two objects, a Cube, and Sphere. 

Raycast in unity

Now we will create a C# script to detect objects through Raycast and destroy them. In this case, we will shoot raycast from cube to a specific range and check if any object gets detected, so we will destroy that.

using UnityEngine;

public class Raycaster : MonoBehaviour
{

    // Update is called once per frame
    void Update()
    {
        RaycastHit hit;

        if (Physics.Raycast(transform.position,
        transform.right, out hit, 5))
        {
            Debug.Log("object name is " + hit.collider.name);
            Destroy(hit.collider.gameObject);
        }

    }
}

We have used Physics.Raycast function for creating ray. In the first parameter, we have given the start point of the ray. In the Second parameter, we have given the direction, In that direction, raycast will go ahead. In the third parameter, we have used out hit this means that whenever raycast will collide with any object so it will return that data into the hit variable. In the fourth Parameter, We have given the length of the raycast, This parameter decides how far the raycast can go, It can also be infinite, depending on the requirement. When we detect any object through raycast we will destroy it.

Note:- Gameobject must have a collider to detect it through the raycast in unity.

You can see the output below.

How to draw ray in unity

Sometimes we want to see the ray drawn in our editor to understand some behavior. Where DrawRay makes it easier for us.

There is a function in unity called Debug.DrawRay. It draws a line from start to start + dir in world coordinates.

Let’s understand it by practical example.

With the help of the above example, we will understand the DrawRay. Here is the example syntax of it:

Debug.DrawRay(transform.position, forward, Color.green);

Let’s extend the above example of the raycast and see how it looks like.

using UnityEngine;

public class Raycaster : MonoBehaviour
{

    // Update is called once per frame
    void Update()
    {
        RaycastHit hit;

        if (Physics.Raycast(transform.position,
        transform.right, out hit, 5))
        {
            Debug.Log("object name is " + hit.collider.name);
            Destroy(hit.collider.gameObject);
        }
        // For Drawing Raycast
        Debug.DrawRay(transform.position,
        transform.right * 5f, Color.red);
    }
}

We just added the Debug.DrawRay function to draw the ray. Let’s understand the parameters of the DrawRay Function. The first parameter is the origin point from where the draw point will start. The second parameter is the direction * Length (how far you want to draw the ray), make sure the length should be the same as the raycast ray length. The third parameter is a simple color, whatever color you want to draw you can give the color here.

Note:- To draw ray in your game/scene you will need to toggle on the Gizmos.

This is how it will look like.

Other Types Of Raycast In Unity

In unity, There are other types of raycast as well. These are different forms of the raycast.

  • RaycastAll
  • 2D Raycast

Let’s understand both one by one.

RaycastAll In Unity

Normally, When you shoot a raycast and when the raycast hit any object so raycast stops itself there only even if there are other objects in the same direction and the raycast has sufficient length as well. 

We can use RaycastAll In case we want to detect multiple objects at the same time. Let’s see how we can use it.

Basics Of RaycastAll In Unity

There are some basic pointers about RaycastAll in unity that we must know before going forward.

  • RaycastHit[]
  • Physics.RaycastAll()

RaycastHit[]:-

RaycastHit[] An array of RaycastHit objects.

It is the same as RaycastHit, It is just an array of RaycastHit. Because when RaycastAll will hit multiple objects so we will need to store multiple elements and that is why it is using an array of RaycastHit.

Physics.RaycastAll() :-

Casts a ray through the Scene and returns all hits.

It is the function that allows you to hit multiple objects at one shoot and return all the objects that have got hit with RaycastAll.

How To Use RaycastAll In Unity?

Now we will practically understand how we can use the RaycastAll in unity. So let’s take a look at the code.

using UnityEngine;

public class RaycastAll : MonoBehaviour
{
    private int rayLength = 15;
    // Update is called once per frame
    void Update()
    {
        RaycastHit[] hits;

        hits = Physics.RaycastAll(transform.position,
        transform.right, rayLength);
        
        foreach (var hit in hits)
        {
            Debug.Log("object name is " + hit.collider.name);
            Destroy(hit.collider.gameObject);
        }
        
        // For Drawing Raycast
        Debug.DrawRay(transform.position,
        transform.right * rayLength, Color.red);
    }
}

In the above code, We have used RaycastAll to get multiple hits. Unlike Raycast it returns the array of RaycastHit. So first we get all the hit points using the RaycastAll physics function after that we loop through all the hit points and can perform any certain action on that. In our case, We destroyed the objects.

In the last we draw the ray, Drawing the ray is the same as we did in the Raycast above. Let’s look at the result.

As you can see above video, As soon as the raycast originates, It destroys all the spheres at once.

Physics2D.Raycast In Unity

As the name suggests, It is a 2D form of the raycast. We can use it in our 2D games for detecting the 2D element. 2D Raycast works with the 2D Physics engine in unity, as it works with the  2D Physics, the 2D element that we want to detect must have a 2D Collider attached to it.

Let’s understand the basics of the Raycast2D

Basics Of Physics2D.Raycast

So let’s understand the basics of 2D raycast in unity. So here are the variable and functions that we want to understand.

  • RaycastHit2D
  • Physics2D.Raycast()

RaycastHit2D :-

Information returned about an object detected by a raycast in 2D physics.

Unlike RaycastHit It only contain the data related to 2D element because it works with the 2D physics. So we can store the data whenever raycast hit to any 2D gameobject.

Physics2D.Raycast() :-

“RaycastHit2D The cast results returned.”

This function will return the RaycastHit2D. So the element that you want to get detected must have 2D collider.

How To Use Physics2D.Raycast In Unity?

Now we will practically understand how we can use the Physics2D.Raycast in unity. So let’s take a look at the code.

using UnityEngine;

public class Raycast2D : MonoBehaviour
{
    private Camera camera;

    private void Start()
    {
        camera = Camera.main;
    }
    
    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            HitRaycast2D();
        }
    }

    public void HitRaycast2D()
    {
        RaycastHit2D rayHit2D;
        Vector2 position = camera.ScreenToWorldPoint
        (Input.mousePosition);

        rayHit2D = Physics2D.Raycast(position, Vector2.down);

        if (rayHit2D.collider != null)
        {
            Debug.Log($"Object name is {rayHit2D.collider.name}");
        }
    }
}

This is a little bit different from other raycast. In the above code, we shoot 2D Raycast on the left click of the mouse and debug the name of the gameobject in the console.

Let’s break down the above code.

First, We took the main camera because we will need it to convert mouse input from screen point to world point.

In Update, We shoot raycast on mouse click.

In the HitRaycast2D Function First, we declare the RaycastHit2D variable to get the hit data from raycast in unity.

Then we converted the Mouse screen position into the world to make it work with the raycast function. we did it with the help of the camera API ScreenToWorldPoint.

In the last, we are debugging the name of the hit object.

Note:- The 2D gameobject you want to detect must have a 2D collider.

Let’s look at the result.

As you can see in the above video when I clicked on the 2D box, I get the debug in the console, That is what we wanted to do, Great!

Finally, we learned how we can use raycast in unity.

Uses Of Raycast In Game Development

Many of you may be thinking that where can we use it? There are so many use cases of raycast in unity. For Instance 

These are just few examples to use raycast in unity, because it varies according to the requirements.

My Recommend Articles

I hope the article was helpful and you have learned how to use raycast in unity. Comment your thoughts or query in the comment section below. And also subscribe to our blog if you want to get this type of informative content related to game development.

Aakash Solanki
Aakash Solanki

I am a professional unity game developer. I have a passion for creating immersive gaming experiences. For me writing articles feels like giving back to the community we have learned from. My hobbies involve playing games and writing articles and sometimes I also create youtube videos.


Share on social media

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top