Search code examples
unity-game-engineui-toolkit

How to get localPosition of pointer within a VisualElement without a callback


I have an issue with the input system that I can't figure out.

I have a VisualElement (using the UI Toolkit), and I need to get the "localPosition" of the pointer on click. (It's going to be a game for touch and mouse so I use pointer.)

I can get the local position using a callback:

myVisualElement.RegisterCallback<PointerDownEvent>(OnPointerDown, TrickleDown.TrickleDown);

Then in the function:

private void OnPointerDown(PointerDownEvent evt)
    {
        pointerLocalPos = evt.localPosition;
    }

But I'm also using the new input system for getting the pressed states (started, canceled, etc.):

InputManager.inputControls.Draw.Click.started += ctx => Click_started(ctx);

Here's the problem. I need to get the localPosition within the VisualElement before or just at the beginning when "Click.started" is called. But the Click_started() fucntion will always be called before "OnPointerDown" sets the value for the pointer position. Is there a way to get the localPosition in the "Click_started" function without a callback maybe? Or is there a another of doing this?


Solution

  • If delaying the processing is an option, you could try something like this (untested):

    
    InputManager.inputControls.Draw.Click.started += Click_started;
    
    
    using System.Threading.Tasks;
    
    async void Click_started()
    {
        await Task.Yield();
        // now OnPointerDown should have been called, if it was going to be..
    
    }