Consider the following Unity C# code snippet that casts a ray forward from the origin. What will be printed to the console?
Ray ray = new Ray(Vector3.zero, Vector3.forward); if (Physics.Raycast(ray, out RaycastHit hit, 10f)) { Debug.Log("Hit: " + hit.collider.name); } else { Debug.Log("No hit"); }
Think about what objects are in front of the origin at runtime.
The ray starts at the origin and points forward. If no collider is in that direction within 10 units, the raycast returns false and prints "No hit".
Choose the correct statement about the RaycastHit struct in Unity.
Think about what information you want after a ray hits something.
RaycastHit.distance returns the distance from the ray's origin to the impact point. The other options are incorrect because the collider is not null on hit, the point is the hit location, and the normal is the surface normal at the hit.
Look at this code snippet. The raycast never detects any objects even though there are colliders in front of the camera. What is the problem?
Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward); if (Physics.Raycast(ray, out RaycastHit hit, 5f)) { Debug.Log("Hit: " + hit.collider.name); } else { Debug.Log("No hit"); }
Check the distance parameter and the scene setup.
The ray length is set to 5 units, but the objects are farther than 5 units away, so the raycast never hits them.
Which option contains the correct syntax to perform a raycast and store the hit info?
RaycastHit hit; bool isHit = Physics.Raycast(transform.position, transform.forward, hit, 10f);
Remember how to pass parameters by reference in C# for out variables.
The Physics.Raycast method requires the out keyword before the RaycastHit parameter to store hit information.
Given this code that casts a ray and collects all hits, how many objects will be detected if there are 3 colliders aligned in the ray's path within 15 units?
Ray ray = new Ray(transform.position, transform.forward); RaycastHit[] hits = Physics.RaycastAll(ray, 15f); int count = hits.Length; Debug.Log("Objects hit: " + count);
Think about what Physics.RaycastAll returns.
Physics.RaycastAll returns all colliders hit by the ray within the specified distance, so it will detect all 3 colliders.