UnityRef is currently in early development. Some features may be incomplete and/or not functioning.

UNITYREF

Your Pit Stop For Solving ANYTHING in Unity

ui

[UI Toolkit] Master Percentage Binding for Responsive Layouts

Solution

game designpathfindingmobile developmentcoroutines

Unity 2022.2.x - Unity 6.3.x

Published Mon, Mar 9

Issue

 When attempting to bind the size of a UI Toolkit element to an integer variable in code, the binding defaults to pixel units. Even if percentage units were manually configured in the UI Builder, the data binding system overrides these with absolute pixel values, breaking responsive layouts.

To bind UI Toolkit element sizes as percentages, a custom converter must be implemented to transform numeric values into StyleLength objects using the Length.Percent method.

Explanation

Standard data binding in UI Toolkit assumes integer inputs represent pixel coordinates. To achieve percentage-based scaling, you must explicitly convert the source value into a StyleLength using the Length.Percent factory method.

  1. Create a converter class that implements the IBindingConverter interface.
  2. In the Convert method, cast the incoming object to an integer or float.
  3. Return a new StyleLength constructed via Length.Percent(value).
  4. Apply the converter to your binding using the converter property during initialization.

By returning a StyleLength instead of a primitive number, the layout engine correctly interprets the value as a percentage of the parent container rather than an absolute unit.

Additional Tips:

  • Percentages are relative to the parent’s content rectangle; ensure the parent has defined dimensions.
  • The StyleLength type is used for various properties including width, height, and flexBasis.
  • For two-way binding, ensure your ConvertBack implementation can parse a StyleLength unit type to avoid runtime exceptions.

Copy


using UnityEngine.UIElements;
using System;

public class IntToPercentageConverter : IBindingConverter
{
    public object Convert(object value)
    {
        if (value is int intValue)
        {
            // Converts the integer to a StyleLength percentage
            return new StyleLength(Length.Percent(intValue));
        }
        return new StyleLength(Length.Percent(0));
    }

    public object ConvertBack(object value)
    {
        // Implementation depends on if you need to extract the value from a StyleLength
        throw new NotImplementedException();
    }
}

Related Posts Haven't quite found a solution to your problem? We think these posts might help you.

Content inspired by a Unity discussion post.