Canvas performance

From nlelouche/Unity-SkillForge · View interactive version

Canvas performance is an AI agent skill from the GitHub repository nlelouche/Unity-SkillForge. UI performance optimization for both UGUI Canvas and UI Toolkit runtime.

How to use this skill

Skill file

UI Performance Optimization

Overview

UI performance optimization techniques for Unity Canvas (UGUI) and UI Toolkit. Covers batching, dirty flagging, pooling, and profiling strategies.

When to Use

Performance Comparison

| Aspect | UGUI | UI Toolkit |

|--------|:----:|:----------:|

| Batch breaking | Common issue | Less prone |

| Dirty rebinding | Canvas rebuild | Element repaint |

| Object overhead | GameObject per element | No GameObjects |

| Memory | Higher | Lower |

UGUI Canvas Optimization

┌─────────────────────────────────────────────────────────────┐
│                   CANVAS HIERARCHY                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  BAD (Single Canvas)          GOOD (Split Canvases)        │
│  ┌──────────────────┐        ┌──────────────────┐          │
│  │ Canvas           │        │ Canvas (Static)  │          │
│  │  ├─ HUD          │        │  ├─ Background   │          │
│  │  ├─ Health Bar ⚡ │        │  └─ Title        │          │
│  │  ├─ Score      ⚡ │        ├──────────────────┤          │
│  │  ├─ Minimap    ⚡ │        │ Canvas (Dynamic) │          │
│  │  └─ Background   │        │  ├─ Health Bar   │          │
│  └──────────────────┘        │  └─ Score        │          │
│                               └──────────────────┘          │
│  ⚡ = Frequent updates cause full rebuild                   │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Key Optimizations

| Optimization | Impact | Technique |

|--------------|:------:|-----------|

| Split canvases | High | Separate dynamic/static |

| Disable Raycast Target | Medium | Uncheck on non-interactive |

| Object pooling | High | Reuse list items |

| Disable invisible | Medium | gameObject.SetActive(false) |

| Avoid layout groups | Medium | Use anchors when possible |

| Cache references | Medium | Don't use GetComponent |

UI Toolkit Optimizations

| Optimization | Technique |

|--------------|-----------|

| Avoid style changes | Use USS classes |

| Query once | Cache Q<> results |

| Virtual lists | ListView with virtualization |

| Avoid generateVisualContent | Use built-in elements |

| Reduce hierarchy | Flatten when possible |

Best Practices

Few-Shot Examples

Example 1: Canvas Splitter

User: "Optimize my HUD canvas."

Agent:

Recommended structure:
1. Canvas_Background (Static)
   - Overlay layer 0
   - Background images, frames
   
2. Canvas_HUD_Dynamic (Nested)
   - Health bar, stamina, score
   - Updates frequently
   
3. Canvas_Minimap (Separate)
   - Render Texture display
   - Updates at lower frequency
   
4. Canvas_Popup (Overlay)
   - Dialogs, notifications
   - Only visible when needed

Example 2: Raycast Optimizer

User: "Fix raycast performance."

Agent:

#if UNITY_EDITOR
[MenuItem("Tools/UI/Optimize Raycasts")]
public static void OptimizeRaycasts()
{
    var graphics = FindObjectsOfType<Graphic>();
    int count = 0;
    
    foreach (var g in graphics)
    {
        // Disable raycast on non-Button, non-Toggle elements
        if (g.GetComponent<Selectable>() == null)
        {
            g.raycastTarget = false;
            count++;
        }
    }
    
    Debug.Log($"Disabled raycast on {count} elements");
}
#endif

Example 3: UI Toolkit Pooled List

User: "Efficient scrolling list."

Agent:

// UI Toolkit ListView with virtualization (built-in)
var listView = new ListView(
    itemsSource: _items,
    itemHeight: 50,
    makeItem: () => new ItemView(),
    bindItem: (element, index) => 
    {
        var view = (ItemView)element;
        view.Bind(_items[index]);
    }
);

// Virtualization is automatic - only visible items are created
listView.virtualizationMethod = CollectionVirtualizationMethod.FixedHeight;

Profiling Tips


TDD Contract

⚠️ Legacy Skill — Refactor Pending

Este skill NO tiene tests automatizados aún. El siguiente boilerplate es un punto de partida.

// Escribe estos tests ANTES de implementar:

// Test 1: should [expected behavior] when [condition]
[Test]
public void CanvasPerformance_Should{ExpectedBehavior}_When{Condition}()
{{
    // Arrange
    // TODO: Setup test fixtures
    
    // Act
    // TODO: Execute system under test
    
    // Assert
    Assert.Fail("Not implemented — write test first");
}}

// Test 2: should handle [edge case]
[Test]
public void CanvasPerformance_ShouldHandle{EdgeCase}()
{{
    // Arrange
    // TODO: Setup edge case scenario
    
    // Act
    // TODO: Execute
    
    // Assert
    Assert.Fail("Not implemented");
}}

// Test 3: should throw when [invalid input]
[Test]
public void CanvasPerformance_ShouldThrow_When{InvalidInput}()
{{
    // Arrange
    var invalidInput = default;
    
    // Act & Assert
    Assert.Throws<Exception>(() => {{ /* execute */ }});
}}

Pasos para completar el TDD:

  1. Descomenta los tests above
  2. Implementa la funcionalidad mínima para que compile
  3. Ejecuta los tests — deben fallar (RED)
  4. Implementa la funcionalidad real
  5. Verifica que los tests pasen (GREEN)
  6. Refactorea manteniendo los tests verdes

Nota: Este skill fue marcado como tdd_first: false durante la auditoría v2.0.1. La sección TDD fue agregada automáticamente pero requiere customización manual para reflejar el comportamiento real del skill.

Related Skills

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.