EditorGUILayout.BeginHorizontal() returns 一个空的 Rect

EditorGUILayout.BeginHorizontal() returns an empty Rect

所以我想格式化自定义 EditorWindow 我正在处理,我在水平布局中组织了所有内容,因此元素非常适合 table 行。

不幸的是,我的 header-row 已关闭,所以我试图通过从 EditorGUILayout.BeginHorizontal() 方法获取基础 Rect 来统一所有内容。

不幸的是,它 return 是一个具有默认值的 Rect(一切都是 0)。所以我无法正常使用它。我是不是遗漏了什么或者为什么 return 是空的 Rect?在 EditorWindow 本身中, space 被填充。

示例代码:

Rect boundary = EditorGUILayout.BeginHorizontal();
float largeWidth = boundary.width * 0.4f;
float smallWidth = boundary.width * 0.2f;
EditorGUILayout.LabelField("stuff1", GUILayout.Width(largeWidth));
EditorGUILayout.LabelField("stuff2", GUILayout.Width(largeWidth));
EditorGUILayout.LabelField("stuff3", GUILayout.Width(smallwidth));
EditorGUILayout.EndHorizontal();

好的,所以我在网上找到了一篇博客文章,说明了显而易见的:

Rect不会被填充,当Object没有多大的时候。当触发不包含信息收集的事件时,信息将可用。

所以我最后做的是:

  • 我在 OnGUI()
  • 开头的字段中保存了 window 宽度(始终可用)
  • 我创建了一些常量来处理所以一切都可以对齐
  • 这些常量只是关于元素之间的间距和左右填充的假设(我知道这些信息可用,但它确实适合,所以我不在乎)

毕竟这是一个肮脏的解决方案,但它确实有效。

这里有一些示例代码供有兴趣的人使用:

public class CustomWindow : EditorWindow
{
    #region Private Fields

    private Vector2 scrollLocation;
    private float elementsWidth;
    private float textBoxWidth;
    private float buttonWidth;
    private const int WINDOW_MIN_SIZE = 400;
    private const int BORDER_SPACING = 10;
    private const int ELEMENT_SPACING = 8;

    #endregion Private Fields

    #region Public Methods

    [MenuItem("Window/CustomWindow")]
    public static void ShowWindow()
    {
        CustomWindow window = GetWindow(typeof(CustomWindow), false, "CustomWindow") as CustomWindow;
        window.Show();
        window.minSize = new Vector2(WINDOW_MIN_SIZE, WINDOW_MIN_SIZE);
        window.Load();
    }

    #endregion Public Methods

    #region Private Methods

    private void OnGUI()
    {
        elementsWidth = EditorGUIUtility.currentViewWidth - BORDER_SPACING * 2;
        textBoxWidth = elementsWidth * 0.4f;
        buttonWidth = elementsWidth * 0.2f;
        scrollLocation = EditorGUILayout.BeginScrollView(scrollLocation);
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("stuff1", GUILayout.Width(largeWidth));
        EditorGUILayout.LabelField("stuff2", GUILayout.Width(largeWidth));
        EditorGUILayout.LabelField("stuff3", GUILayout.Width(smallwidth));
        EditorGUILayout.EndHorizontal();
        EditorGUILayout.EndScrollView();
    }

    #endregion Private Methods
}