Unity UI Best Practices for Performance
Crushing frame rates with your UI? Unity’s UI is powerful, but unoptimized elements can cripple performance. Frame rate drops, especially on mobile, often stem from inefficient UI design. Apply these best practices for smoother gameplay.
If you’re just getting started with game development and need a powerful platform to help you along the way, consider Wayline. Strafekit offers a variety of assets to get your project off the ground, including Low Poly Fantasy Village packs that can give your game a unique visual style.
Understanding the Unity UI Rendering Pipeline
The rendering pipeline dictates how your UI is drawn. Understanding its components is key to optimization.
Canvas Render Modes
- Screen Space - Overlay: Renders UI on top of the scene. Fastest for simple UIs like HUDs that always need to be on top and don’t interact with the 3D scene. Minimizes performance overhead because it requires fewer calculations. Use this for HUDs that always need to be on top and don’t interact with the 3D scene.
- Screen Space - Camera: Renders UI with a specific camera. Allows for depth and effects. Useful for UI that needs to be affected by camera effects or occluded by 3D objects.
- World Space: Renders UI in the 3D world. Use when UI interacts with 3D objects. Example: health bars above characters.
Each mode impacts performance differently. Overlay is generally the cheapest. World Space can be the most expensive due to 3D rendering overhead.
Canvas Rebuilding
Unity batches UI elements for efficient rendering, but changes trigger a costly “rebuild.”
Only parts of the Canvas that change, known as “dirty rectangles,” are redrawn. These areas are tracked by Unity, and only they are updated during a rebuild, saving processing power.
Understanding how dirty rectangles work allows you to strategically group UI elements, minimizing unnecessary redraws and improving performance.
- Batching: Unity tries to draw UI elements together to reduce draw calls.
- Dirty Rectangles: Only parts of the Canvas that change are redrawn.
Minimizing rebuilds is critical. Imagine a health bar updating every frame. Placing the health bar on its own Canvas prevents the entire screen from being redrawn each time the value changes, improving performance. Group static elements on separate canvases.
Overdraw
Overdraw occurs when pixels are drawn multiple times. Transparent UI elements are a major culprit. Reduce overdraw by simplifying UI design and using masks.
Graphic Raycaster
The Graphic Raycaster handles UI input, determining which UI element is clicked. Disable the raycaster on non-interactive elements. Use Physics Raycaster for World Space canvases that require 3D collision.
The Graphic Raycaster is for UI elements; the Physics Raycaster is for 3D objects that need to receive input. Using the wrong raycaster results in unnecessary collision checks, impacting performance.
Optimizing Canvas Usage
Canvases are the foundation of your UI.
Multiple Canvases
Isolate dynamic UI elements on separate canvases. This prevents the entire UI from rebuilding when only a small part changes, improving performance.
Canvas Scaler
The Canvas Scaler controls UI scaling.
- Scale With Screen Size: Adaptable UI for various resolutions.
- Constant Pixel Size: Consistent size; best for fixed resolutions.
Choose the scaling mode that best fits your game and target platform.
Canvas Nesting
Avoid nesting canvases unless absolutely necessary. Nested canvases increase UI complexity and hurt performance.
UI Element Hierarchy
Keep the hierarchy clean and organized. Group similar elements together. A well-organized hierarchy improves batching and reduces draw calls.
Reducing Overdraw and Improving Fill Rate
Overdraw significantly impacts performance, especially on mobile.
UI Masks and Rect Masks
Clip overlapping UI elements to hide obscured areas.
Optimize Image Assets
Use the smallest acceptable resolution and compressed texture formats to reduce memory usage and improve performance. Choose formats like ASTC or ETC2 for mobile, and consider WebP for web-based games.
For UI textures with alpha channels, use ASTC or ETC2 with alpha compression to reduce memory usage without sacrificing visual quality. For UI elements without transparency, consider using a lossy format like JPEG to further reduce file size.
For UI textures, using a Cel Shading: A Comprehensive Expert Guide style visual effect shader can help reduce memory overhead and improve performance.
Transparent Pixels
Minimize transparent pixels. Use solid backgrounds or optimized alpha channels.
Atlasing and Sprite Sheets
Combine multiple UI textures into a single atlas to reduce draw calls.
Efficient UI Layout and Element Management
Layout and element management determine how UI elements are positioned and updated.
Layout Groups
Use layout groups (Horizontal, Vertical, Grid) to automate UI element arrangement. Be mindful of their performance cost, especially with complex layouts.
Content Size Fitter and Aspect Ratio Fitter
Avoid excessive use. They trigger frequent layout calculations. Consider manual sizing or scripting.
Object Pooling
Reuse dynamically created UI elements instead of destroying and recreating them. This reduces garbage collection and improves performance. If you’re looking to implement this, check out our guide on Implementing Object Pooling in Unity for Performance.
Active UI Elements
Minimize active UI elements. Disable UI elements that are not visible. Implement UI element activation/deactivation based on player proximity, view frustum, or other relevance criteria to reduce the rendering load.
Scripting Considerations for UI Performance
UI scripts can easily become performance bottlenecks if you aren’t careful.
Expensive Calculations
Avoid expensive calculations in UI update loops. Perform calculations only when necessary.
Caching UI References
Cache UI references (e.g., GetComponent<Text>()
) to avoid repeated lookups.
Coroutines
Use coroutines for delayed UI updates. This distributes the workload over multiple frames.
Efficient Event Handling
Avoid unnecessary event subscriptions. Subscribe only to the events that are needed.
Text Optimization
Text rendering can be surprisingly expensive.
Text Rendering Modes
- Bitmap: Faster for static text.
- SDF (Signed Distance Field): Better for dynamic text and scaling.
Choose the appropriate rendering mode based on the type of text.
Font Size
Use smaller font sizes to reduce texture memory usage and improve rendering performance.
TextMeshPro
Use TextMeshPro for improved text rendering and performance. It supports SDF rendering and advanced text features.
Dynamic vs. Static Text
Use static text for elements that don’t change frequently. Dynamic text should be used only when necessary.
Profiling and Debugging UI Performance
Profiling is essential for identifying UI performance bottlenecks.
Unity Profiler
Use the Unity Profiler to identify UI performance bottlenecks. Pay attention to CPU usage, draw calls, and memory allocation.
Frame Debugger
Analyze canvas rebuilds and overdraw using the Frame Debugger.
Target Platform
Measure UI performance on target platforms. Performance varies between devices.
Profiler Data
Interpret profiler data and implement targeted optimizations. Don’t optimize blindly.
Alternative UI Solutions and Plugins
Consider alternative UI solutions if Unity’s built-in UI doesn’t meet your needs.
Alternative UI Frameworks
Explore alternative UI frameworks and plugins (e.g., NGUI, UGUI Extensions).
Trade-offs
Evaluate the trade-offs between built-in Unity UI and third-party solutions. Consider alternative UI solutions when your project’s UI requirements exceed the capabilities of built-in Unity UI, or when you are facing unresolvable performance bottlenecks.
Migration
Consider the implications when migrating existing projects to alternative UI solutions. Carefully evaluate the trade-offs between built-in Unity UI and third-party solutions based on your project’s specific needs and performance goals.
Mastering these techniques will not only boost your UI performance but also empower you to create more immersive and engaging user experiences.