We’re using the the UI Toolkit and we love it. For testing purposes, we’d like to have a virtual mouse click on some UI Toolkit buttons to check they do the right thing. Can anyone think of a way to achieve this?
We’re using the new input system so I’m not sure how that affects things.
Thanks for the help
Thanks so much here’s my code for synthesizing a click on a button:
var evt1 = new Event()
{
type = EventType.MouseDown,
button = 0,
mousePosition = buttonCentre,
clickCount = 1
};
using (MouseDownEvent mouseDownEvent = MouseDownEvent.GetPooled(evt1))
{
rootVisualElement.SendEvent(mouseDownEvent);
}
var evt2 = new Event()
{
type = EventType.MouseUp,
button = 0,
mousePosition = buttonCentre,
clickCount = 1
};
using (MouseUpEvent mouseUpEvent = MouseUpEvent.GetPooled(evt2))
{
rootVisualElement.SendEvent(mouseUpEvent);
}
(buttonCentre is any Vector2)
1 Like
For an actual case where you need mouse input to be triggered by code here’s a good working solution. Case in point: Cursor.lockState doesn’t work in Editor properly but will work in Standalone on Mac or PC builds just fine.
For the Editor, I came up with a very legit way by code to move the mouse cursor and another routine to force a mouse click event in the center of the game window because Unity is so annoying in not letting you do this when using Cursor.lockState. Now you can set Cursor.lockState and/or Cursor.visibility in Start() and call either of the following below to force the mouse to behave. (Verified working in macOS Big Sur, Unity 2021.1.17)
Stupid easy way to force mouse cursor position to center of game window in editor only from code:
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.LowLevel;
public static void ForceMousePositionToCenterOfGameWindow()
{
#if UNITY_EDITOR
// Force the mouse to be in the middle of the game screen
var game = UnityEditor.EditorWindow.GetWindow(typeof(UnityEditor.EditorWindow).Assembly.GetType("UnityEditor.GameView"));
Vector2 warpPosition = game.rootVisualElement.contentRect.center; // never let it move
Mouse.current.WarpCursorPosition(warpPosition);
InputState.Change(Mouse.current.position, warpPosition);
#endif
}
Stupid easy way to force click in game window in editor only from code:
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.LowLevel;
public static void ForceClickMouseButtonInCenterOfGameWindow()
{
#if UNITY_EDITOR
var game = UnityEditor.EditorWindow.GetWindow(typeof(UnityEditor.EditorWindow).Assembly.GetType("UnityEditor.GameView"));
Vector2 gameWindowCenter = game.rootVisualElement.contentRect.center;
Event leftClickDown = new Event();
leftClickDown.button = 0;
leftClickDown.clickCount = 1;
leftClickDown.type = EventType.MouseDown;
leftClickDown.mousePosition = gameWindow;
game.SendEvent(leftClickDown);
#endif
}