Unity raycast how and when to use

When I first started game development with Unity I used to stay away from some of the functions that I don’t understand. Unity Raycast is one such function. When I learnt about Raycast then I understood the importance and how Raycast can make a lot of things easier. So, in this post we will be going through some basics of Raycast and then also see some code samples that you can use in your game. Our objective is to make sure you understand the below line of code by the end of the post

Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask)
Unity Raycast cover image

What is Raycast?

Raycast as the name suggests is to casts a ray from one position to another. Its simply like a laser beam in the gaming world. In Unity, Raycast uses mathematical variables like position, range etc to make this possible. You can specify from where to where you want the ray to be cast or you can also cast a ray for an infinite distance in a particular direction. You can also ignore layers during raycasting. Raycast requires colliders in order to interact with the gameobjects. Any gameobject without colliders will not trigger a hit.

When is Raycast used?

Raycast can be used for many purposes in gaming. Mostly it is used to find objects in a particular direction or for shooting. But, one thing to be kept in mind while using Raycast is the affect on performance. You can put many infinite length Raycast then your game performance is going to suffer. The general practice is to Raycast when some action happens. For example, in a shooting script Raycast is done only when the mouse button is pressed.

Unity Raycast code explained

You need to know about a few components before making a proper Raycast.

  1. RaycastHit – this variable type is used to store the information received from the Raycast.
  2. Layermask- this is used to mask one particular layer you want the ray to interact or ignore.
  3. Range – this specifies the range upto which the casted ray will travel. It is always a better option to specify range as it helps in performance.

Lets cast a basic ray from our camera in the forward direction. All you need to do is to attach a script to the camera and add the below line of code to the script

using UnityEngine

public class ExampleClass : MonoBehaviour
{
    
    void FixedUpdate()
    {
         RaycastHit hit;
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, 10))
        {
            
            Debug.Log(hit.gameobject);
        }
        else
        {
            
            Debug.Log("Did not Hit");
        }
    }
}

In the above script we are Raycasting to a range of 10 Units in the forward direction. Physics.Raycast returns true if the ray hit something or else it will return false. In the Raycast syntax the first input is the origin place, second is the direction, third is the output and fourth is the range. We can also add another variable layermask to it. We will discuss about it in the next section. The reason i used fixed update is because Raycast is a physics property and also it will help you to stop Raycasting when you pause your game with timescale.

How to ignore a Raycast layer?

It often comes to a situation where we don’t want the ray to hit everything. For example, implementing friendly fire in a FPS game. You don’t want your fire to hit friends so, you can just add the friendly players to a layer and ignore them from Raycast. To ignore a layer from Raycast you just need to add the bit mask of the layerindex to your raycast expression. You need to add the variable shown below and modify the if statement from the above code. You can also get more information on layermask from Unity manual.

int layerMask = 1 << 5;//bit mask for layer number 5
layerMask=~layerMask
//add the 2nd line if you want to ignore layer 5 if not added it will Raycast only to layer 5

if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, 10, layerMask))

In Unity Raycast is a very helpful function but needs to be used carefully. Many developers avoid Raycast in order to boost performance. But, you need not worry unless you are making a very performance hungry game. Hope the post covered all the required aspects of Raycast. If you have any question you can leave them in the comment section below.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.