How to get editor mouse position properly inside EditorTool API's OnToolGUI()

I’m currently developing a custom tool using the EditorTool API for editing shapes. The tool allows users to manipulate control points that adjust the shape of a 2D mesh.

To detect when the mouse cursor is near the mesh edges, I’m using Event.mousePosition. When the cursor is close to an edge, the tool draws a small yellow handle for adding new control points.

However, I’ve noticed that Event.mousePosition doesn’t update consistently within the OnToolGUI() method of the EditorTool API, leading to some delay in detecting the mouse position.

As a temporary solution, I’m drawing the handles within OnSceneGUI() in a custom inspector while the View Tool (hand icon) is active. In this scenario, Event.mousePosition updates smoothly with no delays.

Is there a way to retrieve the mouse position without the delay when using OnToolGUI()? or Is there a way to replicate the behavior of the View Tool for my tool?

I finally solved the issue! It turns out the problem was related to the control ID, not the position update.

The position was updating correctly, but the handles weren’t being drawn because I needed to assign the default control ID to my tool’s control ID.

Here’s how I fixed it:

public class ShapeEditorTool : EditorTool
    {
        int controlID;

        private void OnEnable()
        {
            controlID = GUIUtility.GetControlID(FocusType.Passive);
        }
        
        public override void OnToolGUI(EditorWindow window)
        {
            if (!(window is SceneView))
                return;
            
            if (!ToolManager.IsActiveTool(this))
                return;
          
            Event currentEvent = Event.current;
            switch (currentEvent.type)
            {
                case EventType.Layout:
                    HandleUtility.AddDefaultControl(controlID);
                    break;
                case EventType.Repaint:
                    // Handles logic here
                    break;
            }
        }
    }
1 Like