Search Unity

Why are GUILayout controls started before the BeginArea they are wrapped in?

Discussion in 'Immediate Mode GUI (IMGUI)' started by vogles, Jul 17, 2015.

  1. vogles

    vogles

    Joined:
    Sep 28, 2009
    Posts:
    131
    I'm working on an editor script and I've got this bit of code:

    Code (csharp):
    1. void OnGUI()
    2. {
    3.     EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
    4.     EditorGUILayout.Space();
    5.     EditorGUILayout.EndHorizontal();
    6.  
    7.     var _sidebar = GUILayoutUtility.GetLastRect();
    8.     _sidebar.x = Screen.width - 400;
    9.     _sidebar.y = _sidebar.height;
    10.     _sidebar.width = 300;
    11.     _sidebar.height = Screen.height - _sidebar.height;
    12.  
    13.     GUI.Box(_sidebar, "");
    14.     GUILayout.BeginArea(_sidebar);
    15.     GUILayout.Button("Area Test");
    16.     GUILayout.EndArea();
    17. }
    For some reason the Button appears above the area specified by the call to BeginArea. Specifically, it behaves as if the origin of the button was bottom left, instead of top left as it should be.

    Here's a screenshot of what's going on:
    BeginArea.PNG
     
  2. martinmr

    martinmr

    Joined:
    Mar 25, 2015
    Posts:
    325
    Just have seen your problem and tried some things out.

    The Problem ist the call of GUILayoutUtiliy.GetLastRect() . Made a DebugLog after the call and printing the _sidebar.height and it was changing between 1 und 18 the hole time.

    So instead of
    _sidebar.y = _sidebar.height -> _sidebar.y = 18;
    _sidebar.height = window.position.height - _sidebar.height; -> _sidebar.height = window.position.height - 18;

    and your problem was fixed.

    Additionally i would prefer instead of Screen.width and Screen.height to use

    var window = EditorWindow.GetWindow(typeof(yourEditorScript));

    and than use

    window.position.width
    window.position.height

    instead. Maybe this will be helpfull in future. If it even makes any difference.

    Best regards

    Code (CSharp):
    1. private const int SPACE = 18;
    2.  
    3. void OnGUI()
    4. {
    5.     EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
    6.     EditorGUILayout.BeginVertical();
    7.      GUILayout.Space(SPACE);
    8.     EditorGUILayout.EndVertical();
    9.     EditorGUILayout.EndHorizontal();
    10.  
    11.     var window = EditorWindow.GetWindow(typeof(myEditorScript));
    12.              
    13.      var _sidebar = new Rect();
    14.      _sidebar.x = window.position.width - 400;
    15.      _sidebar.y = SPACE;
    16.      _sidebar.width = 300;
    17.      _sidebar.height = window.position.height - SPACE;
    18.  
    19.     GUI.Box(_sidebar, "");
    20.     GUILayout.BeginArea(_sidebar);
    21.     GUILayout.Button("Area Test");
    22.     GUILayout.EndArea();
    23. }
     
    Last edited: Jul 20, 2015