[Unity]EditorWindow实现栅格面板

1.效果图

[Unity]EditorWindow实现栅格面板_第1张图片
效果类似Animator面板的工作区。

2.代码

代码如下:

public class NodeEditorWindow : EditorWindow
{   
    private Color backgroundColor;
    private Color gridColor;
    
    [MenuItem("Window/Node Editor")]
    static void OpenEditor() {
        NodeEditorWindow editor = EditorWindow.GetWindow<NodeEditorWindow>();
        editor.Init();
    }
    
    void Init() {
        backgroundColor = new Color(0.4f, 0.4f, 0.4f);
        gridColor = new Color(0.1f, 0.1f, 0.1f);
    }
    
    private void OnGUI()
    {
        DrawBackground();
        DrawGrid(10, 0.2f);
        DrawGrid(50, 0.4f);
    }
    
    private void DrawBackground() {
        EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor);
    }
    
    private void DrawGrid(float gridSpacing, float gridOpacity) {
        int widthDivs = Mathf.CeilToInt(position.width / gridSpacing);
        int heightDivs = Mathf.CeilToInt(position.height / gridSpacing);
        Handles.BeginGUI();
        Handles.color = new Color(gridColor.r, gridColor.g, gridColor.b, gridOpacity);
        offset += drag * 0.5f; Vector3 newOffset = new Vector3(offset.x % gridSpacing, offset.y % gridSpacing, 0);
        for (int i = 0; i < widthDivs; i++)
        {
            Handles.DrawLine(new Vector3(gridSpacing * i, -gridSpacing, 0) + newOffset, new Vector3(gridSpacing * i, position.height, 0f) + newOffset);
        }
        for (int j = 0; j < heightDivs; j++)
        {
            Handles.DrawLine(new Vector3(-gridSpacing, gridSpacing * j, 0) + newOffset, new Vector3(position.width, gridSpacing * j, 0f) + newOffset);
        }
        Handles.color = Color.white;
        Handles.EndGUI();
    }
}

代码包含两个重要方法:
DrawBackground()//绘制背景色.
DrawGrid()//绘制栅格.

你可能感兴趣的:(UnityGUI)