RectSelectionTool.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEditor;
  5. public class RectSelectionTool
  6. {
  7. Vector3 m_StartPoint;
  8. Rect m_Rect;
  9. GUIStyle m_GuiStyle;
  10. public Rect Do(int controlId, Vector3 origin)
  11. {
  12. if (m_GuiStyle == null)
  13. m_GuiStyle = GUI.skin.FindStyle("selectionRect");
  14. Handles.BeginGUI();
  15. Event currentEvent = Event.current;
  16. Ray ray = HandleUtility.GUIPointToWorldRay(currentEvent.mousePosition);
  17. Vector3 forward = Camera.current.transform.forward;
  18. Vector3 up = Camera.current.transform.up;
  19. Vector3 right = Camera.current.transform.right;
  20. Plane plane = new Plane(forward, origin);
  21. float distance;
  22. if (!plane.Raycast(ray, out distance))
  23. return new Rect();
  24. Vector3 worldPoint = ray.GetPoint(distance);
  25. EventType eventType = currentEvent.GetTypeForControl(controlId);
  26. if (eventType == EventType.Layout)
  27. HandleUtility.AddDefaultControl(controlId);
  28. if (eventType == EventType.MouseDown && currentEvent.button == 0)
  29. {
  30. m_StartPoint = worldPoint;
  31. m_Rect = new Rect(m_StartPoint, Vector3.zero);
  32. }
  33. if (GUIUtility.hotControl == controlId && eventType == EventType.Repaint)
  34. m_GuiStyle.Draw(m_Rect, GUIContent.none, false, false, false, false);
  35. EditorGUI.BeginChangeCheck();
  36. worldPoint = Handles.Slider2D(controlId, worldPoint, forward, up, right, 1f, (int cid, Vector3 p, Quaternion q, float s, EventType et) => { }, Vector2.zero);
  37. if (EditorGUI.EndChangeCheck())
  38. m_Rect = FromToRect(HandleUtility.WorldToGUIPoint(m_StartPoint), HandleUtility.WorldToGUIPoint(worldPoint));
  39. Handles.EndGUI();
  40. return m_Rect;
  41. }
  42. Rect FromToRect(Vector2 start, Vector2 end)
  43. {
  44. Rect r = new Rect(start.x, start.y, end.x - start.x, end.y - start.y);
  45. if (r.width < 0)
  46. {
  47. r.x += r.width;
  48. r.width = -r.width;
  49. }
  50. if (r.height < 0)
  51. {
  52. r.y += r.height;
  53. r.height = -r.height;
  54. }
  55. return r;
  56. }
  57. }