Skip to content

Instantly share code, notes, and snippets.

@scho
Last active May 8, 2023 17:19
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scho/81bc72f04da9278d64d79eee1b328784 to your computer and use it in GitHub Desktop.
Save scho/81bc72f04da9278d64d79eee1b328784 to your computer and use it in GitHub Desktop.
Unity UIToolkit Runtime Binding Extension
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine.UIElements;
namespace UI
{
public static class BindingExtensions
{
public static void Bind(this VisualElement element, object data)
{
element.BindValues(data);
if (element.childCount == 0)
{
return;
}
foreach (var child in element.Children())
{
child.Bind(data);
}
}
private static void BindValues(this VisualElement element, object data)
{
if (element is Label label && label.bindingPath != null)
{
foreach (var (name, value) in data.Values())
{
if (label.bindingPath.Equals(name))
{
label.text = (string) value;
}
}
}
}
private static IEnumerable<Tuple<string, object>> Values(this object data)
{
foreach (var fieldInfo in data.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance))
{
yield return Tuple.Create(fieldInfo.Name, fieldInfo.GetValue(data));
}
}
}
}
@FornostAD
Copy link

Hi!
I found this piece of code searching for some solution for UI toolkit Runtime Binding, and have just tried it, but couldn't make it work.

I've followed the same steps that work for Editor Binding (which I found working for runtime but only in play mode, it wont allow you to make a build)

I have an uxml with 6 input fields that bind to variables in my UI interface controller script, I've created a SerializedObject from that script and bind it to the UIDocument, but only one of the input fields shows the correct value of the variable, and 2 way binding is not working either.

Am I skipping some steps?

Thanks!

@scho
Copy link
Author

scho commented Oct 18, 2022

Hey @FornostAD!
The approach in this gist just writes all the values from an object once into a VisualElement.
We no longer use this approach and use UniRx instead together with the following bits:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment