Bird
Raised Fist0
Unityframework~8 mins

Raycasting for detection in Unity - Performance & Optimization

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Performance: Raycasting for detection
MEDIUM IMPACT
Raycasting affects frame rendering speed and input responsiveness by determining object detection costs in the scene.
Detecting objects every frame using raycasting
Unity
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);
        }
    }
}
Raycasting only on mouse click and using layer masks reduces unnecessary physics checks.
📈 Performance GainReduces raycast calls drastically, lowering CPU usage and improving frame rate.
Detecting objects every frame using raycasting
Unity
void Update() {
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, out RaycastHit hit)) {
        Debug.Log(hit.collider.name);
    }
}
Raycasting every frame without filtering causes many expensive physics checks, leading to frame drops.
📉 Performance CostTriggers raycast physics calculations every frame, increasing CPU load and reducing frame rate.
Performance Comparison
PatternRaycast CallsPhysics ChecksCPU LoadVerdict
Raycast every frame without filtersHigh (60+ per second)HighHigh CPU usage, frame drops[X] Bad
Raycast on input event with layer maskLow (on demand)LowLow CPU usage, smooth frames[OK] Good
Rendering Pipeline
Raycasting triggers physics calculations to detect intersections, which can delay frame rendering if overused.
Physics Calculation
CPU Processing
Frame Rendering
⚠️ BottleneckPhysics Calculation stage is most expensive due to collision checks.
Core Web Vital Affected
INP
Raycasting affects frame rendering speed and input responsiveness by determining object detection costs in the scene.
Optimization Tips
1Avoid raycasting every frame; trigger it only on user input or necessary events.
2Use layer masks to limit raycast checks to relevant objects.
3Keep raycast distances as short as possible to reduce physics calculations.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance cost of using raycasting every frame in Unity?
AHigh CPU usage due to frequent physics collision checks
BIncreased GPU load from rendering more objects
CMore memory usage from storing raycast results
DLonger loading times at game start
DevTools: Unity Profiler
How to check: Open Unity Profiler, select CPU Usage, run scene and observe Physics.Raycast calls and CPU spikes.
What to look for: High frequency of raycast calls causing CPU spikes indicates performance issues.

Practice

(1/5)
1. What does raycasting do in Unity?
Raycast is often used to:
easy
A. Send an invisible line to detect objects in a direction
B. Create a visible laser beam effect
C. Change the color of an object
D. Play a sound when an object is clicked

Solution

  1. Step 1: Understand raycasting purpose

    Raycasting sends an invisible line (ray) from a point in a direction to detect objects.
  2. Step 2: Identify correct use

    It is used to check if something is hit by this invisible line, like obstacles or targets.
  3. Final Answer:

    Send an invisible line to detect objects in a direction -> Option A
  4. Quick Check:

    Raycasting = Detect objects with invisible line [OK]
Hint: Raycasting detects objects by sending invisible lines [OK]
Common Mistakes:
  • Thinking raycasting creates visible effects
  • Confusing raycasting with changing object properties
  • Assuming raycasting plays sounds
2. Which of the following is the correct way to start a raycast in Unity C#?
easy
A. Physics.CastRay(origin, direction, hit, maxDistance);
B. Physics.RayCast(origin, direction, hit, maxDistance);
C. Physics.Raycast(origin, direction, out hit, maxDistance);
D. Physics.Raycast(origin, direction, hit, maxDistance);

Solution

  1. Step 1: Recall correct method name and parameters

    The correct method is Physics.Raycast with parameters: origin, direction, out hit, maxDistance.
  2. Step 2: Check syntax correctness

    Only Physics.Raycast(origin, direction, out hit, maxDistance); uses the exact method name and includes out keyword for hit parameter.
  3. Final Answer:

    Physics.Raycast(origin, direction, out hit, maxDistance); -> Option C
  4. Quick Check:

    Correct method and out parameter = Physics.Raycast(origin, direction, out hit, maxDistance); [OK]
Hint: Remember 'out' keyword for hit in Physics.Raycast [OK]
Common Mistakes:
  • Misspelling method name as CastRay or RayCast
  • Omitting 'out' keyword for hit parameter
  • Passing hit without 'out' keyword
3. What will be the output of this code snippet?
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit, 10f)) {
    Debug.Log(hit.collider.name);
} else {
    Debug.Log("No hit");
}

Assuming there is an object named "Target" 5 units ahead in the forward direction.
medium
A. "No hit"
B. "Target"
C. NullReferenceException
D. Empty string

Solution

  1. Step 1: Understand raycast parameters and scene setup

    The raycast starts at the object's position and goes forward 10 units. Since "Target" is 5 units ahead, it will be hit.
  2. Step 2: Analyze output

    Because the ray hits "Target", hit.collider.name will be "Target" and printed.
  3. Final Answer:

    "Target" -> Option B
  4. Quick Check:

    Ray hits object named Target = Output "Target" [OK]
Hint: If object is within distance, raycast hits it [OK]
Common Mistakes:
  • Assuming no hit if object is closer than maxDistance
  • Expecting error instead of hit name
  • Confusing hit.collider.name with hit.transform.name
4. Identify the error in this raycasting code:
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, hit, 10f)) {
    Debug.Log("Hit detected");
}
medium
A. Missing 'out' keyword before hit parameter
B. Wrong method name 'Raycast' should be 'CastRay'
C. transform.forward is invalid direction
D. RaycastHit cannot be used with Physics.Raycast

Solution

  1. Step 1: Check method signature

    Physics.Raycast requires the hit parameter to be passed with the 'out' keyword.
  2. Step 2: Identify missing keyword

    The code passes 'hit' without 'out', causing a compile error.
  3. Final Answer:

    Missing 'out' keyword before hit parameter -> Option A
  4. Quick Check:

    Missing 'out' causes error = Missing 'out' keyword before hit parameter [OK]
Hint: Always use 'out' before hit in Physics.Raycast [OK]
Common Mistakes:
  • Omitting 'out' keyword
  • Changing method name incorrectly
  • Using invalid direction vector
5. You want to detect only objects on the "Enemy" layer using raycasting. Which code snippet correctly does this?
hard
A. int layerMask = LayerMask.NameToLayer("Enemy"); if (Physics.Raycast(origin, direction, out hit, maxDistance, layerMask)) { // hit enemy }
B. int layerMask = 1 << LayerMask.NameToLayer("Enemy"); if (Physics.Raycast(origin, direction, out hit, maxDistance)) { // hit enemy }
C. int layerMask = 1 << LayerMask.NameToLayer("Player"); if (Physics.Raycast(origin, direction, out hit, maxDistance, layerMask)) { // hit enemy }
D. int layerMask = LayerMask.GetMask("Enemy"); if (Physics.Raycast(origin, direction, out hit, maxDistance, layerMask)) { // hit enemy }

Solution

  1. Step 1: Understand layer mask creation

    LayerMask.GetMask("Enemy") returns a mask for the "Enemy" layer correctly for raycasting.
  2. Step 2: Eliminate incorrect options

    int layerMask = 1 << LayerMask.NameToLayer("Enemy"); if (Physics.Raycast(origin, direction, out hit, maxDistance)) { // hit enemy } calculates the layer mask correctly but fails to pass it to the Raycast method, so it detects all layers. int layerMask = 1 << LayerMask.NameToLayer("Player"); if (Physics.Raycast(origin, direction, out hit, maxDistance, layerMask)) { // hit enemy } uses the "Player" layer mask instead of "Enemy". int layerMask = LayerMask.NameToLayer("Enemy"); if (Physics.Raycast(origin, direction, out hit, maxDistance, layerMask)) { // hit enemy } uses LayerMask.NameToLayer("Enemy") without bit shift, creating an invalid layer mask (index instead of bitmask).
  3. Final Answer:

    int layerMask = LayerMask.GetMask("Enemy"); if (Physics.Raycast(origin, direction, out hit, maxDistance, layerMask)) { // hit enemy } -> Option D
  4. Quick Check:

    Use LayerMask.GetMask for correct layer mask [OK]
Hint: Use LayerMask.GetMask("LayerName") for raycast layer filtering [OK]
Common Mistakes:
  • Using NameToLayer without bit shift
  • Using wrong layer name
  • Not applying layer mask in raycast