Can't unregister GeometryChangedEvent

Hi devs! I came to a strange problem, where I can’t unregister an GeometryChangedEvent, and it’s causing an “Layout update is struggling to process current layout” error cause of recursive call.

Here I register callback, note that _tooltip is a static field.

     private static void ShowTooltip(KeyValuePair<VisualElement, TooltipInfo> kvp)
     {
         _tooltip.RegisterCallback<GeometryChangedEvent>((evt) => TooltipGeometryChanged(evt, kvp));
         _tooltip.text = kvp.Key.tooltip;
     }

And right after GeometryChangedEvent is rising:

        private static void TooltipGeometryChanged(GeometryChangedEvent evt, KeyValuePair<VisualElement, TooltipInfo> kvp)
        {
            var target = evt.currentTarget as VisualElement;
            target.UnregisterCallback<GeometryChangedEvent>((evt) => TooltipGeometryChanged(evt,kvp));
            var elementSize = new Vector2(kvp.Key.resolvedStyle.width, kvp.Key.resolvedStyle.height);
            var elementPos = new Vector2(kvp.Key.worldBound.x, kvp.Key.worldBound.y);
            CalcTooltipPos(elementSize, elementPos, kvp.Value);
        }

But despite this line, callback keeps rising in infinite loop =\

target.UnregisterCallback<GeometryChangedEvent>((evt) => TooltipGeometryChanged(evt,kvp));

What am I doing wrong?
Thanks in advance!

Each time you declare an anonymous delegate (lambda) like that, it’s a new thing, not the same thing you added, even if it looks identical.

Instead, assign the delegate to a variable you keep track of, add it, then remove it.

3 Likes

Additionally, I would add that there exists a version of RegisterCallback that allows you to capture an object and receive it in your callback. Just like a lambda, this will capture a variable and make it persist with the callback, but it allows you to unregister the same way.

// Send user data along to the callback
myElement.RegisterCallback<MouseDownEvent, MyType>(MyCallbackWithData, myData);

Unity - Manual: Handle events (see Send custom data to an event callback)

2 Likes

Thanks a lot, I’ll keep it in mind!

Thank you, It works fine!