Performance: Raycasting for detection
Raycasting affects frame rendering speed and input responsiveness by determining object detection costs in the scene.
Jump into concepts and practice - no test required
void Update() {
if (Input.GetMouseButtonDown(0)) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit, maxDistance, layerMask)) {
Debug.Log(hit.collider.name);
}
}
}void Update() {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit)) {
Debug.Log(hit.collider.name);
}
}| Pattern | Raycast Calls | Physics Checks | CPU Load | Verdict |
|---|---|---|---|---|
| Raycast every frame without filters | High (60+ per second) | High | High CPU usage, frame drops | [X] Bad |
| Raycast on input event with layer mask | Low (on demand) | Low | Low CPU usage, smooth frames | [OK] Good |
Raycast is often used to:Physics.Raycast with parameters: origin, direction, out hit, maxDistance.out keyword for hit parameter.RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit, 10f)) {
Debug.Log(hit.collider.name);
} else {
Debug.Log("No hit");
}hit.collider.name will be "Target" and printed.RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, hit, 10f)) {
Debug.Log("Hit detected");
}