Search Unity

Check if dragging or clicking a control during runtime

Discussion in 'UI Toolkit' started by JakHussain, Jul 27, 2020.

  1. JakHussain

    JakHussain

    Joined:
    Oct 20, 2016
    Posts:
    318
    With UGUI I would normally do something like this:

    Code (CSharp):
    1. public static bool IsMouseOverUIObject ()
    2. {
    3.     if (EventSystem.current != null)
    4.     {
    5.         PointerEventData eventDataCurrentPosition = new PointerEventData (EventSystem.current)
    6.         {
    7.             position = new Vector2 (Input.mousePosition.x, Input.mousePosition.y)
    8.         };
    9.  
    10.         List<RaycastResult> results = new List<RaycastResult> ();
    11.         EventSystem.current.RaycastAll (eventDataCurrentPosition, results);
    12.  
    13.         return results.Count > 0;
    14.     }
    15.     else
    16.     {
    17.         Debug.LogError ("No EventSystem present to check for 'InputValidation.IsMouseOverUIObject ()'.");
    18.         return false;
    19.     }
    20. }
    To check if the mouse was above some interactable object so that when I dragged a slider, I could stop my camera from spinning.

    How would I go about doing this with UIToolkit for runtime?
     
  2. uDamian

    uDamian

    Unity Technologies

    Joined:
    Dec 11, 2017
    Posts:
    1,231
    You can use a state-machine of Events. UI Toolkit calls this a "Manipulator". Here's an example that lets you click+drag an element:
    https://github.com/Unity-Technologi...ssets/QuickIntro/Editor/FloatingDemoWindow.cs

    The example also captures the mouse so all events while holding down the left button are sent to the same element, even if the mouse is no longer on top of it. If you only care about MouseEnter/MouseLeave (no clicking), then just monitor for those two events on your element and maintain a "mouse is currently over me" variable if needed.