Unity Essentials: Physics, UI & Gameplay Systems

Lesson 2 of 8

Raycasting

A raycast shoots an invisible line through the scene and reports what it hits, the basis for shooting, line-of-sight checks, and click-to-move.

using UnityEngine;

public class Shooter : MonoBehaviour
{
    public float range = 100f;

    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
            Shoot();
    }

    void Shoot()
    {
        if (Physics.Raycast(transform.position, transform.forward, out RaycastHit hit, range))
        {
            Debug.Log($"Hit {hit.collider.gameObject.name} at distance {hit.distance}");
            hit.collider.GetComponent<IDamageable>()?.TakeDamage(10);
        }
    }
}

The pieces

  • Physics.Raycast(origin, direction, out RaycastHit hit, maxDistance) returns true if the ray hit something within maxDistance, and fills hit with details (the collider, exact point, distance, surface normal).
  • out parameters (like RaycastHit hit) let a method return extra information beyond its normal return value, hit is only meaningful if Raycast returned true.
  • A layer mask (an optional extra parameter) restricts which layers the ray can hit, e.g. ignoring the player's own collider when shooting.

Debugging rays

Debug.DrawRay(origin, direction * range, Color.red, duration) draws a visible line in the Scene view (not in the actual game), invaluable for seeing exactly where a raycast is pointing while you're testing.

📝 Raycasting Quiz

Passing score: 70%
  1. 1.What does Physics.Raycast return?

  2. 2.The ____ parameter on Raycast lets the method return extra hit details alongside its bool result.

  3. 3.Debug.DrawRay makes a ray visible to players in the built game.