0
0
Unityframework~8 mins

Obstacle avoidance in Unity - Performance & Optimization

Choose your learning style9 modes available
Performance: Obstacle avoidance
MEDIUM IMPACT
This affects the frame rate and responsiveness of the game by how often and how complex the obstacle detection and avoidance calculations are.
Detecting and avoiding obstacles for a moving character in a game scene
Unity
void Update() {
  if (Time.frameCount % 5 == 0) {
    RaycastHit hit;
    if (Physics.Raycast(transform.position, transform.forward, out hit, 10f)) {
      if (hit.collider.CompareTag("Obstacle")) {
        transform.Rotate(0, 90, 0);
      }
    }
  }
  transform.Translate(Vector3.forward * Time.deltaTime * speed);
}
Limits raycast checks to every 5 frames, reducing physics calls and smoothing CPU usage.
📈 Performance Gainreduces physics raycasts by 80%, lowering CPU load and improving frame rate stability
Detecting and avoiding obstacles for a moving character in a game scene
Unity
void Update() {
  RaycastHit hit;
  if (Physics.Raycast(transform.position, transform.forward, out hit, 10f)) {
    if (hit.collider.CompareTag("Obstacle")) {
      transform.Rotate(0, 90, 0);
    }
  }
  transform.Translate(Vector3.forward * Time.deltaTime * speed);
}
This runs a raycast every frame without any optimization, causing many physics checks and potential frame drops.
📉 Performance Costtriggers 1 physics raycast per frame, causing CPU spikes especially with many moving objects
Performance Comparison
PatternPhysics CallsCPU UsageFrame DropsVerdict
Raycast every frameHigh (1 per frame)HighFrequent[X] Bad
Raycast every 5 framesLow (1 per 5 frames)LowRare[OK] Good
Rendering Pipeline
Obstacle avoidance calculations run on the CPU and affect the game loop update cycle. Frequent physics raycasts increase CPU usage and can delay frame rendering.
Game Loop Update
Physics Calculation
⚠️ BottleneckPhysics Calculation stage due to frequent raycasts
Optimization Tips
1Avoid running physics raycasts every frame if possible.
2Use simpler colliders and limit raycast targets to reduce cost.
3Batch or space out obstacle detection checks to smooth CPU usage.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance cost of running obstacle avoidance with raycasts every frame?
AHigh CPU usage due to frequent physics raycasts
BIncreased GPU load from rendering
CMore memory usage from storing raycast results
DLonger loading times at game start
DevTools: Unity Profiler
How to check: Open Unity Profiler, run the game, and look at CPU Usage and Physics sections to see how many raycasts are called per frame.
What to look for: High spikes in Physics raycast calls indicate inefficient obstacle avoidance; smoother CPU usage means better performance.