Intro

Raycast is a physics function in Unity that casts a ray from a point of origin in a certain direction and distance to detect collisions with objects that have colliders. It returns true if an object was hit and provides a RaycastHit variable to store information about the hit object, such as its position, distance, and transform.

Resources

Raycasts in Unity, made easy

Sample Implementation

  • Notes
    • Vector3.forward vs transform.forward 1
      • Vector3 is world space
      • transform is relative to the object its attached to
    • MonoBehaviour- a component on a physical object, script must be attached to a GameObject
using UnityEngine;
 
public class PhysicsRayCast : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }
    
    // Update is called once per frame
    void Update()
    {
        RaycastHit hit;
        if (Physics.Raycast(transform.position, transform.forward, out hit, 100f)){
            Debug.Log(hit.collider.name);
        }
 
        Debug.DrawLine(transform.position, transform.forward*100f);
    }
}

Footnotes

  1. https://www.youtube.com/watch?v=j9F6kEB9rBg&t=7s