Unity Editor mouse clicks in 3D Viewport

Hello all!

I started working on a custom editor for a project, and this editor requires to react on mouse clicks in the 3D editor viewport.

I was able to use a CustomEditor and overwriting the EventType.layout with setting the selection to an empty array and HandleUtility.AddDefaultControl. However, this allows me only to get one mouse click, and not check if the mouse was released again. Plus, of course, this is a really unclean “hacky” solution, which I would like to avoid.

Basically I just want to poll the mouse position every frame, check if the mouse button (and which one) was pressed, and from there on I think I will be fine.

Thanks in advance,
ReiAyanami

I was able to do it without using AddDefaultControl. This is in my customEditor script for my polygon create tool. Seems to work pretty well for me.

public void OnSceneGUI()
{
  Event e = Event.current;

  //Check the event type and make sure it's left click.
  if ((e.type == EventType.MouseDrag || e.type == EventType.MouseDown)  e.button == 0)
  {
     /* Do stuff
        * * * *
      * */
     e.Use();  //Eat the event so it doesn't propagate through the editor.
  }
}
1 Like

Thanks for the answers.

I was finally able to figure out a good solution with your help and this thread.

Thanks again!

In case anyone else stumbles across this thread (as I did) looking for guidance on handling mouse input with custom handles, you can save yourself the time I ended up spending on it by reading my answer here:

http://answers.unity3d.com/questions/463207/how-do-you-make-a-custom-handle-respond-to-the-mou.html

For people who need to have a SceneView mouse position outside a class that has OnSceneGUI(), for example, a menu invoke, plugin, or whatever…

/// <summary>
/// This is used to find the mouse position when it's over a SceneView.
/// Used by tools that are menu invoked.
/// </summary>
[InitializeOnLoad]
public class MouseHelper : Editor
{
    private static Vector2 position;

    public static Vector2 Position
    {
        get { return position; }
    }

    static MouseHelper()
    {
        SceneView.onSceneGUIDelegate += UpdateView;
    }

    private static void UpdateView(SceneView sceneView)
    {
        if (Event.current != null)
            position = new Vector2(Event.current.mousePosition.x + sceneView.position.x, Event.current.mousePosition.y + sceneView.position.y);
    }
}
5 Likes