Skip to content

1. Overview

Joni Savolainen edited this page May 26, 2023 · 13 revisions

About

The goal of UIComponents is to ease the creation of reusable components when working with Unity's new UIToolkit system. It offers ways to load UXML and USS files automatically, and decouple your UI code from other systems via dependency injection.

Requirements

UIComponents officially supports Unity 2021.3 or newer. Unity's com.unity.roslyn package can be used to enable source generation in Unity 2020. Refer to the Installation section below for more information.

Example usage

using UnityEngine.UIElements;
using UIComponents;

[UxmlName("Counter")] // A UxmlFactory implementation is generated.
[Layout("CounterComponent/CounterComponent")]
[Stylesheet("CounterComponent/CounterComponent.style")]
[Stylesheet("Common")]
[Dependency(typeof(ICounterService), provide: typeof(CounterService))]
public partial class CounterComponent : UIComponent, IOnAttachToPanel
{
    // The layout and stylesheets are loaded automatically.
    // They are retrieved from Resources by default,
    // hence the lack of file extensions.
    
    // An UxmlTraits implementation is generated automatically for this class.
    [UxmlTrait]
    public string IncrementText = "Increment";
    
    // Queries are made after all assets have loaded.
    // The query calls are generated automatically for you.
    [Query("count-label")]
    public Label CountLabel;
    
    [Query("increment-button")]
    public Button IncrementButton;
    
    // An instance of CounterService is injected into this field
    // in the inherited constructor.
    [Provide]
    private ICounterService _counterService;
    
    // The OnInit method is called after all assets have loaded.
    // Any operations related to the DOM and stylesheets should
    // be done here.
    public override void OnInit()
    {
        CountLabel.text = _counterService.Count.ToString();
        IncrementButton.text = IncrementText;
    }
    
    // Event handlers are registered after all assets have loaded.
    // To listen for events, all you need to do is implement
    // a supported interface.
    public void OnAttachToPanel(AttachToPanelEvent evt)
    {
        CountLabel.text = _counterService.Count.ToString();
    }
}

Instantiation in code:

var container = new VisualElement();
container.Add(new CounterComponent() { IncrementText = "+1" });

Instantiation in UXML:

<Counter increment-text="+1" />

UIComponents are VisualElements with protected virtual methods which are overridden via source generation. Those virtual methods are called when the UIComponent is first attached to a panel.

Testing

The UIComponents package has been designed with testability in mind. The UIComponents.Testing assembly contains the TestBed helper class.

using UIComponents;
using UIComponents.Testing;
using NUnit.Framework;
using UnityEngine.TestTools;

[TestFixture]
public class CounterComponentTests
{
    private TestBed _testBed;
    private ICounterService _counterService;
    
    [SetUp]
    public void SetUp()
    {
        // A mocking framework like NSubstitute is recommended.
        // Here we don't use a mock at all.
        _counterService = new CounterService();
        _testBed = TestBed.Create()
            .WithSingleton<ICounterService>(_counterService)
            .Build();
    }
    
    [UnityTest]
    public IEnumerator It_Initializes_Count_Label_On_Init()
    {
        _counterService.Count = 42;

        var component = _testBed.CreateComponent<CounterComponent>();
        // UIComponents start their initialization when they are first attached to a panel.
        // We can force the initialization by calling Initialize() manually.
        component.Initialize();
        // Wait until the component's assets have been loaded.
        yield return component.WaitForInitializationEnumerator();
        Assert.That(component.CountLabel.text, Is.EqualTo("42"));
    }
}

Installation

Note: See the current version here. This article refers to it as X.Y.Z.

With OpenUPM (recommended)

openupm add io.savolainen.uicomponents

Alternatively, merge this snippet to your Packages/manifest.json file:

{
    "scopedRegistries": [
        {
            "name": "package.openupm.com",
            "url": "https://package.openupm.com",
            "scopes": [
                "io.savolainen.uicomponents"
            ]
        }
    ],
    "dependencies": {
        "io.savolainen.uicomponents": "X.Y.Z"
    }
}

With Git

Add this under dependencies in your Packages/manifest.json file:

"io.savolainen.uicomponents": "https://github.com/jonisavo/uicomponents.git#upm/vX.Y.Z"

This will install version X.Y.Z.

To update, change upm/vX.Y.Z to point to the latest version.

With .unitypackage

Download the latest .unitypackage from the releases page.

To update, remove the existing files and extract the new .unitypackage.

For Unity 2020

After installing UIComponents, install the com.unity.roslyn package. This enables source generation in Unity 2020.

Add this under dependencies in your Packages/manifest.json file:

"com.unity.roslyn": "0.2.2-preview"

You may need to restart Unity.

Clone this wiki locally