How to Use Raycast in Unity: Syntax and Example
In Unity, use
Physics.Raycast to shoot an invisible line (ray) from a point in a direction to detect objects it hits. You provide the ray's origin, direction, and optionally get info about what it hits using a RaycastHit object.Syntax
The basic syntax of Physics.Raycast involves specifying the starting point and direction of the ray. You can also get detailed hit information by using a RaycastHit variable.
- origin: The starting point of the ray in world space.
- direction: The direction in which the ray is cast.
- out hitInfo: Stores information about what the ray hits.
- maxDistance: The maximum length the ray should check for collisions.
csharp
bool Physics.Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo, float maxDistance);Example
This example casts a ray from the camera's position forward and prints the name of the object it hits, if any.
csharp
using UnityEngine; public class RaycastExample : MonoBehaviour { void Update() { RaycastHit hit; Vector3 origin = Camera.main.transform.position; Vector3 direction = Camera.main.transform.forward.normalized; float maxDistance = 100f; if (Physics.Raycast(origin, direction, out hit, maxDistance)) { Debug.Log("Hit object: " + hit.collider.gameObject.name); } else { Debug.Log("No object hit"); } } }
Output
When running, the console logs the name of the first object the ray hits in front of the camera or 'No object hit' if none.
Common Pitfalls
- Not normalizing the direction vector can cause unexpected behavior.
- Forgetting to set a reasonable
maxDistancemay cause the ray to check infinitely far. - Ignoring layers can cause the ray to hit unwanted objects; use layer masks to filter.
- Not checking the return value of
Physics.Raycastbefore accessinghitInfocauses errors.
csharp
/* Wrong way: Not checking if ray hits before using hitInfo */ RaycastHit hit; Physics.Raycast(origin, direction, out hit, maxDistance); Debug.Log(hit.collider.gameObject.name); // May cause error if no hit /* Right way: Check if ray hits before using hitInfo */ RaycastHit hit; if (Physics.Raycast(origin, direction, out hit, maxDistance)) { Debug.Log(hit.collider.gameObject.name); }
Quick Reference
- Physics.Raycast: Casts a ray and returns true if it hits an object.
- RaycastHit: Stores info about the hit like position, normal, and collider.
- origin: Start point of the ray.
- direction: Direction to cast the ray (should be normalized).
- maxDistance: How far the ray checks.
- LayerMask: Use to filter which objects the ray can hit.
Key Takeaways
Use Physics.Raycast with origin, direction, and RaycastHit to detect objects in 3D space.
Always check the boolean result of Physics.Raycast before using hit information.
Normalize the direction vector to ensure correct raycasting behavior.
Set a maxDistance to limit how far the ray checks for collisions.
Use layer masks to filter which objects the ray can hit for better performance.