Raycasting helps your game check if something is in front of an object. It works like shining a flashlight or laser to see what it hits.
0
0
Raycasting for detection in Unity
Introduction
To check if the player can see an enemy.
To detect if there is a wall in front before moving.
To find out if a bullet hits a target.
To interact with objects by pointing at them.
To check if the ground is below the player.
Syntax
Unity
Physics.Raycast(origin, direction, out RaycastHit hitInfo, maxDistance)
origin: where the ray starts (a point in space).
direction: the way the ray points (a vector).
Examples
This shoots a ray from the object forward up to 10 units and prints the name of what it hits.
Unity
if (Physics.Raycast(transform.position, transform.forward, out RaycastHit hit, 10f)) { Debug.Log("Hit: " + hit.collider.name); }
This ray points down to check if the ground is within 5 units below.
Unity
Ray ray = new Ray(transform.position, Vector3.down); if (Physics.Raycast(ray, out RaycastHit hitInfo, 5f)) { Debug.Log("Ground detected at distance: " + hitInfo.distance); }
Sample Program
This script checks every frame if there is an object in front of the player within 10 units. It prints the object's name or says nothing is detected.
Unity
using UnityEngine; public class RaycastDetector : MonoBehaviour { void Update() { if (Physics.Raycast(transform.position, transform.forward, out RaycastHit hit, 10f)) { Debug.Log($"Detected object: {hit.collider.name}"); } else { Debug.Log("Nothing detected in front."); } } }
OutputSuccess
Important Notes
Make sure objects you want to detect have colliders attached.
Raycasting only detects objects on layers that are not ignored by the raycast.
You can adjust maxDistance to control how far the ray checks.
Summary
Raycasting sends an invisible line to detect objects in a direction.
Use it to check for obstacles, targets, or interactable items.
Remember to set origin, direction, and max distance carefully.