Search Unity

How does this work? HandleUtility.FindNearestVertex

Discussion in 'Editor & General Support' started by MvNimwegen, Jun 21, 2021.

  1. MvNimwegen

    MvNimwegen

    Joined:
    Dec 19, 2019
    Posts:
    56
    I am trying to use vertex snapping in the scene GUI. I found this method in this documentation but I cannot get it to function properly. I input a GUI point, given by the example given in this GUI Point documentation, but the output Vector3 vertex seems very random to me.

    This is the code I used to test this method
    Code (CSharp):
    1.     private void OnSceneGUI()
    2.     {
    3.         //Set sphere color
    4.         Handles.color = Color.red;
    5.  
    6.         //Get the mouse position
    7.         Vector2 mousePos = Event.current.mousePosition;
    8.        
    9.         //Convert it to a gui point
    10.         Vector2 guiPoint = GUIUtility.ScreenToGUIPoint(mousePos);
    11.  
    12.         //Find the nearest vertex to that gui point
    13.         bool found = HandleUtility.FindNearestVertex(guiPoint, out Vector3 vertex);
    14.        
    15.         //Draw a sphere on that vertex
    16.         Handles.SphereHandleCap(0, vertex, Quaternion.identity, HandleUtility.GetHandleSize(vertex) * .2f, EventType.Repaint);
    17.  
    18.         //Log results
    19.         Debug.Log(found + ": " + vertex);
    20.     }
    This is what it looked like in the Scene View

    8xCz8E21ys.gif

    I expected the Sphere to snap to vertices close to the mouse cursor, but it does not do that.

    Could someone maybe explain to me how to use this properly?

    Thanks!
     
  2. MvNimwegen

    MvNimwegen

    Joined:
    Dec 19, 2019
    Posts:
    56
    Okay so I already solved it.
    This method does exactly work as advertised. However, the Scene View wasn't repainting as fast as I expected it to do. Because of this, the Sphere did not follow the mouse properly: it lagged behind. If I add
    Sceneview.RepaintAll()
    at the end of the code, it all works fine!