0
0
Unityframework~8 mins

Anchoring and responsive UI in Unity - Performance & Optimization

Choose your learning style9 modes available
Performance: Anchoring and responsive UI
MEDIUM IMPACT
Anchoring affects how UI elements resize and reposition during screen size changes, impacting rendering and layout recalculations.
Making UI elements adapt smoothly to different screen sizes
Unity
RectTransform rt = GetComponent<RectTransform>();
rt.anchorMin = new Vector2(0.5f, 0.5f);
rt.anchorMax = new Vector2(0.5f, 0.5f);
rt.anchoredPosition = Vector2.zero; // center anchored
rt.sizeDelta = new Vector2(200, 50); // size relative to anchors
Anchoring UI elements relative to parent reduces layout recalculations and prevents visual shifts on different screen sizes.
📈 Performance GainSingle layout calculation on resize, reduces visual instability (CLS)
Making UI elements adapt smoothly to different screen sizes
Unity
RectTransform rt = GetComponent<RectTransform>();
rt.anchoredPosition = new Vector2(100, 100); // fixed position
rt.sizeDelta = new Vector2(200, 50); // fixed size
Fixed positions and sizes cause UI elements to not adapt, triggering layout recalculations and visual shifts on different screens.
📉 Performance CostTriggers multiple layout recalculations and visual shifts on screen resize
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Fixed position and sizeHigh (many recalculations)Multiple on resizeHigh due to layout shifts[X] Bad
Relative anchoring with flexible positionsLow (minimal recalculations)Single on resizeLow, stable visuals[OK] Good
Rendering Pipeline
Anchoring affects the Layout and Paint stages by controlling how UI elements resize and reposition when the screen changes size.
Layout
Paint
Composite
⚠️ BottleneckLayout stage due to recalculations on screen resize
Core Web Vital Affected
CLS
Anchoring affects how UI elements resize and reposition during screen size changes, impacting rendering and layout recalculations.
Optimization Tips
1Use relative anchors instead of fixed positions for UI elements.
2Avoid hardcoding sizes; let UI scale with screen size.
3Test UI on multiple resolutions to ensure stable layout and minimal recalculations.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using relative anchoring in Unity UI?
AReduces layout recalculations and visual shifts on screen resize
BIncreases the number of draw calls for better visuals
CMakes UI elements fixed size for consistency
DDisables UI rendering to save resources
DevTools: Unity UI Profiler
How to check: Open the UI Profiler during screen resize or resolution change; observe layout recalculations and draw calls.
What to look for: Look for fewer layout rebuilds and stable draw calls indicating efficient anchoring and responsive UI