Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Editor tool drawn in scene view stickied to mouse.

Discussion in 'Scripting' started by sand_lantern, Jul 8, 2020.

  1. sand_lantern

    sand_lantern

    Joined:
    Sep 15, 2017
    Posts:
    210
    I am working on a little tool built into an editor window. When I press a hotkey, I want that tool to be stickied to the mouse position and to draw some lines in the scene view. At first I had this working by using gizmos and an actual object in the scene, but I wanted my tool to work with just an editor window and not a game object.

    It was pretty straight forwards to do this, and I *almost* had it working but ran into a little snag. In order to get things drawing I was using Handles.DrawLine by tethering my draw function something like this.
    Code (CSharp):
    1. public class ToolWindow : EditorWindow
    2. {      
    3.    private void OnEnable ()
    4.    {
    5.       SceneView.onSceneGUIDelegate += OnSceneGUI;
    6.    }
    7.  
    8.    internal void OnSceneGUI (SceneView scene)
    9.    {
    10.       if (sticky)
    11.       {
    12.          Vector3 position = Event.current.mousePosition;
    13.          position = position.SetY (scene.camera.pixelHeight - position.y);
    14.          Ray worldRay = scene.camera.ScreenPointToRay (position);
    15.          tool.MoveToRay (worldRay, new Plane (tool.Normal, tool.Center));
    16.       }
    17.       DrawMyTool(tool);
    18.    }
    19.  
    20.    [MenuItem ("Tools/MyTool/Move #R")]
    21.    public static void MoveTool ()
    22.    {
    23.       GetWindow<ToolWindow> ("Tool", true).ToggleSticky ();
    24.    }
    25. }
    Unfortunately, this only happens every second or so so the stickied tool is very jerky and not a smooth experience.

    So I tried to resolve this by switching from
    SceneView.onSceneGUIDelegate += OnSceneGUI
    to
    EditorApplication.update += OnSceneGUI


    Unfortunately, I was unable to get this to work because I don't have access to any of the current Events so while this seems to happen frequently enough for a smooth movement, it messes up the mouse movement.

    I can always move back to just having my tool as a gameobject in scene but I certainly would like to avoid that if possible. Surely there's a way to do what I'm trying to do. Any suggestions out there?
     
    Last edited: Jul 8, 2020
  2. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190