2017-02-22 111 views
0

如何在Unity中创建交互式GUI对象 - 编辑器窗口如何让四边形可以在Unity Editor窗口中拖放?

enter image description here

我可以得出静态四边形如下面的代码。但我想要的效果像reference video,从0:220:30

public class EditorCanvas { 
    public static void DrawQuad(int x, int y, int width, int height, Color color) { 
     Rect rect = new Rect(x, y, width, height); 
     Texture2D texture = new Texture2D(1, 1); 
     texture.SetPixel(0, 0, color); 
     texture.Apply(); 
     GUI.skin.box.normal.background = texture; 
     GUI.Box(rect, GUIContent.none); 
    } 
} 


public class MyWindow : EditorWindow { 
    void OnGUI() { 
     EditorCanvas.DrawQuad(100, 75, 50, 50, Color.black); 
    } 
} 

回答

1

你可以声明一个包含你盒子当前位置的矩形。在此示例中,该位置初始化为0,0,大小为100,100

然后,每次移动鼠标时(EventType.MouseDrag),您将自上次事件(Event.delta)后的鼠标移动添加到框位置。

为了获得平稳拖动,你必须告诉团结你有一个事件,所以他可以重画。 (Event.use

Rect _boxPos = new Rect(0, 0, 100, 100); 

void OnGUI() 
{ 
    if (Event.current.type == EventType.MouseDrag && 
     _boxPos.Contains(Event.current.mousePosition)) 
    { 
     _boxPos.position += Event.current.delta; 
    } 

    GUI.Box(_boxPos, "test"); 

    if (Event.current.isMouse) 
     Event.current.Use(); 
} 

所以现在你可以轻松地适应您的DrawQuad方法。