Skip to content

Unity Raycast Tutorial: How to Raycast, Detect Objects and Draw Ray Lines

Table of Contents

How to use Raycast in unity – complete topicwise Tutorial

Unity Raycast is one of those features that looks complicated when you first see it in a project, but the basic idea is actually very simple.

You send an invisible ray from one point in a direction and ask Unity:

“Did this ray hit anything?”

This simple question can be used for a surprising number of gameplay systems.

You can use a raycast to detect an object in front of the player, shoot a weapon, check the ground, interact with objects, detect walls, find where the mouse is pointing, or create a simple enemy vision system.

Unity provides this functionality through Physics.Raycast() for the 3D physics system.

In this Unity Raycast tutorial, we’ll start with a basic example and gradually build it into more practical examples. We’ll cover RaycastHit, LayerMasks, mouse raycasting, downward raycasts, drawing raycast lines, debugging, and some common mistakes.

If you’re working on a 2D game using Collider2D components, see our separate guide on Raycast Unity 2D and Physics2D.Raycast(). This article focuses on the 3D Physics.Raycast() API.


What Is a Raycast in Unity?

Think of a raycast as an invisible straight line.

You give Unity:

  • A starting position
  • A direction
  • A maximum distance
  • Optionally, a LayerMask

Unity then checks whether the ray intersects a collider.

For example:

Player
  |
  |----------------------------> Enemy
             Ray

If the ray reaches the enemy’s collider, Unity reports a hit.

That’s the basic idea behind a Unity Raycast.

The ray itself doesn’t push the object, move it, or damage it. It is simply a physics query.

You decide what should happen after the raycast detects something.

For example:

Raycast
   ↓
Did we hit something?
   ↓
Yes
   ↓
What object did we hit?
   ↓
Apply gameplay logic

That separation is important because the same raycast can be used for completely different gameplay systems.


How to Raycast in Unity with Physics.Raycast

Unity Raycast tutorial showing raycast line and object detection
Unity Raycast tutorial showing raycast line and object detection

Let’s start with the simplest possible example.

using UnityEngine;

public class RaycastExample : MonoBehaviour
{
    [SerializeField] private float rayDistance = 10f;

    private void Update()
    {
        if (Physics.Raycast(
            transform.position,
            transform.forward,
            rayDistance))
        {
            Debug.Log("Something is in front of the player.");
        }
    }
}

This is enough to perform a basic raycast.

The important part is:

Physics.Raycast(
    transform.position,
    transform.forward,
    rayDistance
);

There are three important values here.

Origin

The origin tells Unity where the ray starts:

transform.position

Direction

The direction tells Unity where the ray should travel:

transform.forward

This means the ray travels in the forward direction of the GameObject.

Distance

The distance determines how far the ray should check:

rayDistance

If rayDistance is 10, the ray checks up to 10 Unity units away.

The basic Physics.Raycast API supports an origin, direction and maximum distance, with additional parameters available for layer filtering and trigger handling.


How to Use Raycast Unity with RaycastHit

The previous example only tells us whether something was hit.

Usually, we also want to know what was hit.

That’s where RaycastHit comes in.

using UnityEngine;

public class RaycastExample : MonoBehaviour
{
    [SerializeField] private float rayDistance = 10f;

    private void Update()
    {
        RaycastHit hit;

        if (Physics.Raycast(
            transform.position,
            transform.forward,
            out hit,
            rayDistance))
        {
            Debug.Log("Hit: " + hit.collider.name);
        }
    }
}

Now we can inspect the object that was detected.

For example:

hit.collider.name

can give us the name of the GameObject that owns the collider.

RaycastHit also provides other useful information.

Property What it gives you
hit.collider Collider that was hit
hit.point Exact hit position
hit.distance Distance from ray origin
hit.normal Surface direction at the hit
hit.rigidbody Rigidbody associated with the collider
hit.transform Transform of the hit object

For many gameplay systems, the two properties you’ll use most often are:

hit.collider

and:

hit.point

A Better Unity Raycast Example

Once you understand the basic syntax, I recommend writing the raycast in a way that’s easy to modify later.

using UnityEngine;

public class PlayerRaycast : MonoBehaviour
{
    [SerializeField] private float rayDistance = 10f;

    private void Update()
    {
        Vector3 origin = transform.position;
        Vector3 direction = transform.forward;

        if (Physics.Raycast(
            origin,
            direction,
            out RaycastHit hit,
            rayDistance))
        {
            Debug.Log(
                $"Hit {hit.collider.name} at {hit.point}"
            );
        }
    }
}

This version makes the three important parts very clear:

Origin
Direction
Distance

That becomes particularly useful when you start creating more advanced raycast systems.


How to Draw Raycast Line Unity

One of the first things you’ll probably ask after creating a raycast is:

“How can I see the ray?”

By default, a raycast is not a visible object in your game.

For debugging, Unity provides:

Debug.DrawRay()

For example:

private void Update()
{
    Vector3 origin = transform.position;
    Vector3 direction = transform.forward;
    float distance = 10f;

    Debug.DrawRay(
        origin,
        direction * distance
    );

    if (Physics.Raycast(
        origin,
        direction,
        out RaycastHit hit,
        distance))
    {
        Debug.Log("Hit: " + hit.collider.name);
    }
}

Debug.DrawRay() draws a line starting at the supplied position and extending by the supplied direction vector. By default, it is visible for one frame, so calling it from Update() keeps the line visible while the game is running.

This is probably the easiest answer to how to draw raycast line Unity.


How to See Raycast Unity in the Scene View

If you’re debugging a raycast and it doesn’t appear to work, don’t guess.

Draw the ray.

For example:

Debug.DrawRay(
    transform.position,
    transform.forward * 10f
);

Then:

  1. Enter Play Mode.
  2. Open the Scene view.
  3. Select the GameObject containing the script.
  4. Make sure Gizmos are enabled.
  5. Look at the direction of the line.
  6. Check whether it reaches the object you’re trying to detect.

This is one of the simplest ways to answer how to see Raycast Unity.

Unity’s documentation notes that Debug.DrawRay draws in the Scene view, and it can also appear in the Game view when gizmo drawing is enabled.

Why is this useful?

Because many raycast problems aren’t actually raycast problems.

For example, you might think:

“My raycast isn’t detecting the enemy.”

But after drawing the ray, you discover:

Player
 |
 |----->

                 Enemy

The ray was simply pointing in the wrong direction.

Debug visualization can save a lot of time.


Drawing Only the Part of the Ray That Hits

Sometimes you don’t want to draw the complete ray.

You may want to draw the line only up to the object that was detected.

For that, use Debug.DrawLine():

private void Update()
{
    Vector3 origin = transform.position;
    Vector3 direction = transform.forward;
    float distance = 10f;

    if (Physics.Raycast(
        origin,
        direction,
        out RaycastHit hit,
        distance))
    {
        Debug.DrawLine(
            origin,
            hit.point
        );
    }
    else
    {
        Debug.DrawRay(
            origin,
            direction * distance
        );
    }
}

Now the debugging behavior is:

No hit:

Player -------------------------->

Hit:

Player ---------------> Enemy
                       *
                     hit.point

This is particularly useful when working on weapons, interaction systems, or AI vision.


How to Raycast Unity with a LayerMask

By default, you may not want your raycast to detect every collider.

Imagine your scene contains:

  • Player
  • Enemy
  • Ground
  • Environment
  • Weapon
  • Pickup
  • Decorative objects

If the player is shooting, you probably only care about certain layers.

That’s where LayerMask becomes useful.

Create a field:

[SerializeField] private LayerMask targetLayer;

Then use it with the raycast:

if (Physics.Raycast(
    transform.position,
    transform.forward,
    out RaycastHit hit,
    10f,
    targetLayer))
{
    Debug.Log("Target hit: " + hit.collider.name);
}

Now you can select the layers the raycast should detect from the Inspector.

This is better than detecting everything and then writing extra code to ignore objects you don’t care about.

Unity’s Physics.Raycast API supports a LayerMask specifically to selectively ignore colliders during the raycast.


Unity Raycast Ignore Layer

Sometimes you want the opposite behavior.

Instead of saying:

“Only detect this layer.”

you might want:

“Detect everything except this layer.”

You can create a mask using bitwise operations:

int layerMask = ~LayerMask.GetMask("Player");

Then:

if (Physics.Raycast(
    transform.position,
    transform.forward,
    out RaycastHit hit,
    10f,
    layerMask))
{
    Debug.Log("Hit: " + hit.collider.name);
}

This is useful when you don’t want the ray to hit the player who is casting it.

However, for most gameplay code, I prefer configuring a serialized LayerMask in the Inspector because it makes the intended layers easier to understand and change.


Raycast From Mouse Unity

Unity Raycast tutorial showing raycast line and object detection
Unity Raycast tutorial showing raycast line and object detection

Mouse raycasting is one of the most common practical uses of a Unity raycast.

Suppose you have a 3D game where the player clicks on an object.

The mouse position is in screen space, but your 3D scene uses world space.

So we first convert the mouse position into a world-space ray using:

Camera.main.ScreenPointToRay(Input.mousePosition)

Unity’s ScreenPointToRay creates a world-space ray that starts from the camera’s near plane and passes through the specified screen position.

Here’s a simple example:

using UnityEngine;

public class MouseRaycast : MonoBehaviour
{
    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(
                Input.mousePosition
            );

            if (Physics.Raycast(
                ray,
                out RaycastHit hit,
                100f))
            {
                Debug.Log(
                    "Clicked: " + hit.collider.name
                );
            }
        }
    }
}

The flow is:

Mouse position
      ↓
ScreenPointToRay()
      ↓
World-space Ray
      ↓
Physics.Raycast()
      ↓
Object detected

This technique is useful for:

  • Clicking 3D objects
  • Strategy games
  • RTS games
  • Object selection
  • Interaction systems
  • Point-and-click mechanics
  • Editor-style tools

Raycast From Mouse to Select an Object

You can build on the previous example to create a simple object-selection system.

private void Update()
{
    if (!Input.GetMouseButtonDown(0))
        return;

    Ray ray = Camera.main.ScreenPointToRay(
        Input.mousePosition
    );

    if (Physics.Raycast(
        ray,
        out RaycastHit hit,
        100f))
    {
        GameObject selectedObject =
            hit.collider.gameObject;

        Debug.Log(
            "Selected: " + selectedObject.name
        );
    }
}

Now clicking an object gives you the actual GameObject.

From there, you could:

  • Highlight it
  • Open an information panel
  • Move the character toward it
  • Select it for an RTS command
  • Start an interaction
  • Show its stats

The raycast only handles the detection. The rest belongs to your gameplay system.


Unity Raycast Down for Ground Detection

Another very common use is a downward raycast.

For example, a character may need to know whether it is standing on the ground.

using UnityEngine;

public class GroundCheck : MonoBehaviour
{
    [SerializeField] private float groundDistance = 1f;
    [SerializeField] private LayerMask groundLayer;

    private void Update()
    {
        bool isGrounded = Physics.Raycast(
            transform.position,
            Vector3.down,
            groundDistance,
            groundLayer
        );

        if (isGrounded)
        {
            Debug.Log("Player is grounded.");
        }
    }
}

The important part is:

Vector3.down

This tells Unity to cast the ray downward.

This is a simple Unity Raycast Down example.

You can use it for:

  • Ground detection
  • Checking if an object is above a surface
  • Detecting platforms
  • Checking terrain
  • Simple character controllers

One important limitation

A single ray only checks one narrow point.

Imagine a large character:

     Player
  ┌──────────┐
  │          │
  │    ↓     │
  │    |     │
  └────|─────┘
       |
     Ground

If the center point is over empty space while part of the character is over a platform, the ray may return no hit.

For more reliable character-ground detection, a SphereCast, CapsuleCast, BoxCast, or overlap check may be a better fit depending on the shape of your character.


Unity Raycast for Shooting

Raycasts are commonly used for hitscan weapons.

A hitscan weapon checks the target immediately instead of spawning a physical bullet and waiting for it to travel.

Here’s a simple example:

using UnityEngine;

public class WeaponRaycast : MonoBehaviour
{
    [SerializeField] private Transform firePoint;
    [SerializeField] private float range = 100f;
    [SerializeField] private LayerMask targetLayer;

    public void Shoot()
    {
        Vector3 origin = firePoint.position;
        Vector3 direction = firePoint.forward;

        if (Physics.Raycast(
            origin,
            direction,
            out RaycastHit hit,
            range,
            targetLayer))
        {
            Debug.Log(
                "Shot hit: " + hit.collider.name
            );
        }
    }
}

You could call:

Shoot();

when the player presses the fire button.

This approach works well for:

  • Guns
  • Lasers
  • Sniper weapons
  • Instant-hit attacks
  • Interaction weapons

It isn’t always the right choice.

If you want a bullet that physically travels through the world, a projectile with a Rigidbody and collision detection may make more sense.


Applying Damage After a Raycast Hit

The raycast should normally be responsible for detecting the target, not managing the target’s entire health system.

For example:

private void Shoot()
{
    if (Physics.Raycast(
        firePoint.position,
        firePoint.forward,
        out RaycastHit hit,
        range,
        targetLayer))
    {
        Enemy enemy =
            hit.collider.GetComponent<Enemy>();

        if (enemy != null)
        {
            enemy.TakeDamage(10);
        }
    }
}

The flow becomes:

Weapon
  ↓
Raycast
  ↓
Collider detected
  ↓
Find gameplay component
  ↓
TakeDamage()

Keeping these responsibilities separate makes the code easier to change later.

For example, you could replace the Enemy component with a general health interface without having to completely rewrite the raycast logic.


Unity Raycast for Object Interaction

Raycasts are also useful for interaction systems.

Imagine the player is looking at a door.

Instead of checking every door in the scene, cast a ray forward:

[SerializeField] private float interactionDistance = 3f;
[SerializeField] private LayerMask interactionLayer;

private void Update()
{
    if (Physics.Raycast(
        transform.position,
        transform.forward,
        out RaycastHit hit,
        interactionDistance,
        interactionLayer))
    {
        Debug.Log(
            "Interactive object: " +
            hit.collider.name
        );
    }
}

You can use this for:

  • Doors
  • NPCs
  • Switches
  • Buttons
  • Items
  • Machines
  • Pickups
  • Signs

A useful pattern is to give interactive objects their own component:

public interface IInteractable
{
    void Interact();
}

Then your raycast system can detect the object and call its interaction method.

This keeps your interaction logic separate from the detection logic.


Unity Raycast for Wall Detection

A raycast can also check whether a wall is directly ahead.

[SerializeField] private float wallDistance = 1f;
[SerializeField] private LayerMask wallLayer;

private bool IsWallAhead()
{
    return Physics.Raycast(
        transform.position,
        transform.forward,
        wallDistance,
        wallLayer
    );
}

Then:

if (IsWallAhead())
{
    Debug.Log("Wall detected.");
}

This can be useful for simple movement systems, AI, or environment checks.

Again, remember that a single ray represents only a single line.

If you need to check the full width of a character, a shape cast is often more appropriate.


Creating a Simple Line of Sight System

Another useful application of Raycast Unity is checking whether one object can see another.

Suppose an enemy wants to check whether the player is visible.

First calculate the direction:

Vector3 direction =
    (player.position - transform.position)
    .normalized;

Then calculate the distance:

float distance =
    Vector3.Distance(
        transform.position,
        player.position
    );

Now perform the raycast:

[SerializeField] private Transform player;
[SerializeField] private LayerMask obstacleLayer;

private bool CanSeePlayer()
{
    Vector3 origin = transform.position;

    Vector3 direction =
        (player.position - origin).normalized;

    float distance =
        Vector3.Distance(
            origin,
            player.position
        );

    return !Physics.Raycast(
        origin,
        direction,
        distance,
        obstacleLayer
    );
}

The idea is simple:

Enemy ---------------------- Player
              ↑
          clear path?

If the ray hits an obstacle first, the player is blocked.

If it doesn’t hit anything, the path is clear.

For a more complete AI vision system, you would usually combine this with distance and field-of-view checks.


Understanding Raycast Distance

The distance parameter is important.

For example:

Physics.Raycast(
    origin,
    direction,
    5f
);

means the ray only checks five units.

If your target is 10 units away, it won’t be detected.

Player

|---------|---------|
         5          10
                    Enemy

The ray ends before reaching the enemy.

Increase the distance:

Physics.Raycast(
    origin,
    direction,
    10f
);

and the target can now be detected.

In gameplay code, avoid using an unnecessarily large distance. Set the range based on what the system actually needs.


What Happens When a Raycast Hits Nothing?

A raycast returns false when no collider is detected within the specified conditions.

For example:

if (Physics.Raycast(
    transform.position,
    transform.forward,
    out RaycastHit hit,
    10f))
{
    Debug.Log("Hit: " + hit.collider.name);
}
else
{
    Debug.Log("Nothing detected.");
}

This makes raycasts convenient for simple yes/no checks.

You can think of it as:

Raycast
   ↓
Hit?
 ┌───┴───┐
Yes     No
 ↓       ↓
Hit     Nothing

Common Unity Raycast Problems

If your Unity Raycast isn’t working, check the basics before changing your code.

The Object Doesn’t Have a Collider

A raycast detects colliders.

Check that your target has an appropriate 3D collider such as:

BoxCollider
SphereCollider
CapsuleCollider
MeshCollider

If you’re using BoxCollider2D, CircleCollider2D, or another 2D collider, you need the 2D physics API instead.


You’re Using Physics.Raycast with a 2D Collider

This is an easy mistake.

For 3D:

Physics.Raycast()

For 2D:

Physics2D.Raycast()

Don’t mix the two systems.

Your 2D article should cover Physics2D.Raycast() separately.


The Ray Is Pointing the Wrong Way

Add:

Debug.DrawRay(
    transform.position,
    transform.forward * 10f
);

Then inspect the Scene view.

You may find that the ray is pointing away from the target.


The Ray Is Too Short

Temporarily increase the distance:

Physics.Raycast(
    transform.position,
    transform.forward,
    100f
);

If the ray starts detecting the object, your original distance was probably too small.


The LayerMask Is Wrong

If you are using:

LayerMask targetLayer

make sure the target GameObject is actually on one of the selected layers.

A LayerMask can silently filter out the object you’re trying to detect.

For troubleshooting, temporarily remove the LayerMask:

Physics.Raycast(
    transform.position,
    transform.forward,
    out RaycastHit hit,
    10f
);

If this works, check your layer configuration.


The Ray Starts Inside a Collider

The starting position also matters.

If the ray starts inside a collider, the result may not behave as you expect. Unity specifically documents that raycasts do not detect a collider when the ray origin is already inside that collider.

If you’re getting unexpected results, visualize the origin and check its position relative to nearby colliders.


How to Debug a Raycast Properly

When I have a raycast problem, I normally don’t start by changing random parameters.

I visualize it first.

For example:

Vector3 origin = transform.position;
Vector3 direction = transform.forward;
float distance = 10f;

Debug.DrawRay(
    origin,
    direction * distance
);

Then check these four things:

1. Is the origin correct?

Is the ray starting where you expect?

2. Is the direction correct?

Is it pointing toward the object?

3. Is the distance long enough?

Does the ray actually reach the target?

4. Is the LayerMask correct?

Is the target included in the layers being checked?

These four checks solve a large number of raycast problems.


Raycast vs Ray

You will often see both Ray and Physics.Raycast() in Unity code.

They are related but not the same thing.

A Ray represents:

Origin + Direction

For example:

Ray ray = new Ray(
    transform.position,
    transform.forward
);

The ray itself doesn’t perform collision detection.

You then pass it to Physics.Raycast():

if (Physics.Raycast(
    ray,
    out RaycastHit hit,
    10f))
{
    Debug.Log(hit.collider.name);
}

This can make code such as mouse raycasting easier to understand because Camera.ScreenPointToRay() already returns a Ray.


How to Draw a Raycast Line in Unity

There are two common debugging methods.

Debug.DrawRay

Use it when you have:

Origin + Direction

Example:

Debug.DrawRay(
    origin,
    direction * distance
);

Debug.DrawLine

Use it when you have two positions.

For example:

Debug.DrawLine(
    origin,
    hit.point
);

This is useful when you want to show exactly where a raycast hit.

A simple debugging example:

private void Update()
{
    Vector3 origin = transform.position;
    Vector3 direction = transform.forward;

    if (Physics.Raycast(
        origin,
        direction,
        out RaycastHit hit,
        10f))
    {
        Debug.DrawLine(
            origin,
            hit.point
        );
    }
    else
    {
        Debug.DrawRay(
            origin,
            direction * 10f
        );
    }
}

Should You Use Raycast Every Frame?

It depends on what you’re building.

A single raycast isn’t automatically a performance problem.

But if you have hundreds of objects each performing many raycasts every frame, the total number of physics queries can become significant.

A few practical rules:

Don’t raycast when you don’t need to

For shooting:

if (Input.GetMouseButtonDown(0))
{
    Shoot();
}

Cast the ray when the player actually shoots instead of checking every frame.

Use a LayerMask

Don’t check objects that your system doesn’t care about.

Keep the distance reasonable

Don’t cast 500 units if the gameplay system only needs 5.

Don’t use RaycastAll unnecessarily

If you only need the first hit, use:

Physics.Raycast()

instead of:

Physics.RaycastAll()

For high-frequency systems, profile the actual game before making optimization decisions.


Raycast vs RaycastAll

Normal raycast:

Physics.Raycast()

is useful when you need the first relevant hit.

For example:

Player --------> Enemy

If the enemy is the first collider hit, that’s usually all you need.

But imagine:

Player ---> Enemy ---> Wall ---> Object

If you need information about multiple objects along the ray, use:

RaycastHit[] hits = Physics.RaycastAll(
    transform.position,
    transform.forward,
    20f
);

Then:

foreach (RaycastHit hit in hits)
{
    Debug.Log(hit.collider.name);
}

Use RaycastAll because you actually need multiple results, not simply because it seems more powerful.


A Complete Unity Raycast Example

Here is a small script that brings the important concepts together:

using UnityEngine;

public class SimpleUnityRaycast : MonoBehaviour
{
    [SerializeField] private float distance = 10f;
    [SerializeField] private LayerMask targetLayer;

    private void Update()
    {
        Vector3 origin = transform.position;
        Vector3 direction = transform.forward;

        if (Physics.Raycast(
            origin,
            direction,
            out RaycastHit hit,
            distance,
            targetLayer))
        {
            Debug.DrawLine(
                origin,
                hit.point
            );

            Debug.Log(
                $"Hit: {hit.collider.name}"
            );

            Debug.Log(
                $"Point: {hit.point}"
            );

            Debug.Log(
                $"Distance: {hit.distance}"
            );
        }
        else
        {
            Debug.DrawRay(
                origin,
                direction * distance
            );
        }
    }
}

Attach this script to a GameObject and create a few objects with colliders in front of it.

Then configure the Target Layer in the Inspector.

When you press Play, you can use the Scene view to see the ray and the Console to see the detected object.

This gives you a simple starting point for experimenting with Unity Raycast.


When Should You Use Raycast in Unity?

Raycast is a good choice when your question is directional.

For example:

Is something directly in front of me?

What did my weapon hit?

Is there ground below me?

Is there an obstacle between these two objects?

Which object did the player click?

Those are good raycast problems.

But not every detection problem needs a ray.

Requirement Better option
Detect something along a line Raycast
Check an area around an object OverlapSphere
Check a larger physical shape SphereCast / BoxCast / CapsuleCast
Check between two known points Linecast
Detect continuous physical contact Collider / collision system

Choosing the right physics query can make your gameplay code much simpler.


Final Thoughts

Once you understand how to raycast Unity, the API becomes much less intimidating.

The basic pattern is:

Physics.Raycast(
    origin,
    direction,
    distance
);

Then you add the features you actually need:

Raycast
   ↓
RaycastHit
   ↓
LayerMask
   ↓
Debug.DrawRay
   ↓
Gameplay logic

From this small building block, you can create:

  • Object detection
  • Shooting
  • Mouse selection
  • Ground checks
  • Wall detection
  • Object interaction
  • Enemy line of sight
  • Simple AI detection

The most useful habit is to visualize your ray when debugging.

If a raycast isn’t working, check the origin, direction, distance, collider, and LayerMask before assuming something is wrong with the API.

And remember that this article uses Unity’s 3D physics system:

Physics.Raycast()

If you’re developing a 2D game, use the corresponding 2D physics API:

Physics2D.Raycast()

The idea is similar, but keeping the 2D and 3D implementations as separate topics makes your code and your documentation much easier to follow.


Frequently Asked Questions

What is Unity Raycast?

A Unity Raycast is a physics query that sends a ray from an origin in a specific direction and checks whether it intersects a collider. In the 3D physics system, this is done with Physics.Raycast().

How to Raycast in Unity?

The simplest way is:

if (Physics.Raycast(
    transform.position,
    transform.forward,
    10f))
{
    Debug.Log("Something was detected.");
}

For more information about the detected object, use RaycastHit.

How to Use Raycast Unity with RaycastHit?

Use the out parameter:

if (Physics.Raycast(
    transform.position,
    transform.forward,
    out RaycastHit hit,
    10f))
{
    Debug.Log(hit.collider.name);
}

This gives you information about the collider that was hit.

How to Draw Raycast Line Unity?

Use:

Debug.DrawRay(
    transform.position,
    transform.forward * 10f
);

You can view the debug line in the Unity Scene view while the game is running.

How to See Raycast in Unity?

Use Debug.DrawRay() or Debug.DrawLine() and look at the Scene view while the game is running. Make sure Gizmos are enabled.

How to Raycast From Mouse Unity?

Convert the mouse position into a world-space ray:

Ray ray = Camera.main.ScreenPointToRay(
    Input.mousePosition
);

Then pass that ray to:

Physics.Raycast(ray, out RaycastHit hit);

ScreenPointToRay creates a world-space ray passing through the supplied screen position.

How to Use Unity Raycast Down?

Use Vector3.down:

Physics.Raycast(
    transform.position,
    Vector3.down,
    2f
);

This is commonly used for simple ground detection.

How Do I Ignore a Layer in Unity Raycast?

Use a LayerMask to control which layers the raycast can detect:

[SerializeField] private LayerMask targetLayer;

Then pass it to Physics.Raycast().

What Is the Difference Between Physics.Raycast and Physics2D.Raycast?

Physics.Raycast() is used with Unity’s 3D physics system, while Physics2D.Raycast() is used with Unity’s 2D physics system.

Use Physics.Raycast() with 3D colliders and Physics2D.Raycast() with 2D colliders See more on Raycast unity 2d.

Should I Use Raycast or RaycastAll?

Use Physics.Raycast() when you need the relevant first hit.

Use Physics.RaycastAll() when you actually need multiple hits along the ray.

Can Raycast Detect an Object Without a Collider?

No. A physics raycast needs a collider to detect the object.

If your GameObject isn’t being detected, check whether it has an appropriate 3D Collider component and whether your LayerMask allows that layer.

Is Raycast Expensive in Unity?

A single raycast is generally not something you should worry about prematurely. Performance depends on how many physics queries your game performs and how often they run.

If your project performs a large number of raycasts, profile the actual game and optimize based on measured results.

Leave a Reply

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