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)returnstrueif the ray hit something withinmaxDistance, and fillshitwith details (the collider, exact point, distance, surface normal).outparameters (likeRaycastHit hit) let a method return extra information beyond its normal return value,hitis only meaningful ifRaycastreturnedtrue.- 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.