Hi, I’m not sure what’s the current support for UnityEvent in UI Builder, but I’ve run into the following issue:
I have simple custom Button
element with UxmlAttribute
of UnityClickEvent
:
using UI.Events;
using UnityEngine.UIElements;
namespace UI.Lib
{
[UxmlElement]
public partial class Button : UnityEngine.UIElements.Button
{
[UxmlAttribute] public UnityClickEvent onClicked;
protected override void HandleEventTrickleDown(EventBase evt)
{
base.HandleEventTrickleDown(evt);
if (evt is ClickEvent clickEvent)
{
onClicked.Invoke(clickEvent);
}
}
}
}
Here is the UnityClickEvent
class which simply inherits from generic UnityEvent
(AFAIK there is not way to serialize generics) and serialized using JsonUtility
.
using System;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UIElements;
namespace UI.Events
{
[Serializable]
public class UnityClickEvent : UnityEvent<ClickEvent>
{
}
public class UnityClickEventConverter : UxmlAttributeConverter<UnityClickEvent>
{
public override UnityClickEvent FromString(string value) => JsonUtility.FromJson<UnityClickEvent>(value);
public override string ToString(UnityClickEvent value) => JsonUtility.ToJson(value);
}
}
Now this is works fine for most of the time even after the editor restarts, but sometimes it just randomly breaks the reference by assigning some random rubbish even though serialised value inside the UXML file didn’t change.
Before:
After: