RaycastHit
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 34 of 63.
Physics.Raycast can also tell you what it hit. Add out RaycastHit hit after the direction: when the method returns true, it has filled hit with the details. out is how a C# method hands back an extra value through a variable you give it. This rangefinder logs what it points at, and how far away it is, when you press Space:
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
if (Physics.Raycast(transform.position, transform.forward, out RaycastHit hit, 50f))
{
Debug.Log(hit.collider.name + " is " + hit.distance + " units away");
}
}
}Pointed at a wall whose front is 12 units ahead, it logs Wall is 12 units away. The other fields: hit.point is the spot in the world where the ray touched the surface, hit.normal is the direction the surface faces at that spot ((0, 1, 0) on flat ground), and hit.transform is the Transform of the object that was hit. Through hit.collider.gameObject you reach anything else about it, such as its tag.
Read hit only inside the if. When the ray misses, Raycast returns false and hit holds nothing useful: its collider is null.
Challenge
MediumGive the gun a laser sight. The LaserSight script sits on the Gun, and the Inspector gives it the red dot (a Transform) and a range of 15. The left and right arrows turn the gun.
- Every frame, cast a ray from the gun along its own forward,
rangeunits long. - When it hits, show the dot and put it exactly where the ray touched the surface.
- When it hits nothing, hide the dot with
SetActive(false).
The Dot is on the Ignore Raycast layer, so the ray passes through the dot itself. Press Play and sweep the laser over the wall, the crate and the barrel, then Check.
Try it yourself
using UnityEngine;
public class LaserSight : MonoBehaviour
{
public Transform dot;
public float range = 15f;
void Update()
{
// Put the dot where the laser meets a surface; hide it when the laser hits nothing.
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall