1 2 3 4 5 6 7 8 9 |
switch (Event.current.type) { case EventType.MouseDrag: var pos = Event.current.mousePosition; Debug.Log(pos); label.Position = pos; Repaint(); break; } |
Unity中GUI的事件都在Event中,Event.current表示当前窗口的事件,比如这个MouseDrag表示鼠标拖动的事件,利用这个可以实现Editor中拖动控件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Vector2 labelPos = new Vector2(100, 100); private void OnGUI() { switch (Event.current.type) { case EventType.MouseDrag: var pos = Event.current.mousePosition; labelPos = pos; Repaint(); break; } GUI.Label(new Rect(labelPos, new Vector2(50, 50)), "测试"); } |
事件一览(https://docs.unity3d.com/ScriptReference/EventType.html):
MouseDown | Mouse button was pressed. |
MouseUp | Mouse button was released. |
MouseMove | Mouse was moved (Editor views only). |
MouseDrag | Mouse was dragged. |
KeyDown | A keyboard key was pressed. |
KeyUp | A keyboard key was released. |
ScrollWheel | The scroll wheel was moved. |
Repaint | A repaint event. One is sent every frame. |
Layout | A layout event. |
DragUpdated | Editor only: drag & drop operation updated. |
DragPerform | Editor only: drag & drop operation performed. |
DragExited | Editor only: drag & drop operation exited. |
Ignore | Event should be ignored. |
Used | Already processed event. |
ValidateCommand | Validates a special command (e.g. copy & paste). |
ExecuteCommand | Execute a special command (eg. copy & paste). |
ContextClick | User has right-clicked (or control-clicked on the mac). |
MouseEnterWindow | Mouse entered a window (Editor views only). |
MouseLeaveWindow | Mouse left a window (Editor views only). |