- Home /
GUIStyle and GUILayout size
I have question about GUIStyle.
I often apply GUIStyle to GUILayout and some GUIStyle expand GUILayout even if I dont assign size.
void OnGUI() {
EditorGUILayout.BeginHorizontal();
{
left();
right();
}
EditorGUILayout.EndHorizontal();
}
private void left() {
EditorGUILayout.BeginVertical();
{
GUILayout.Box( "default box", GUI.skin.box );
GUILayout.Box( "default box", GUI.skin.box );
}
EditorGUILayout.EndVertical();
}
private void right() {
EditorGUILayout.BeginVertical();
{
GUILayout.Box( "RL Background", new GUIStyle( "RL Background" ) );
GUILayout.Box( "RL Background", new GUIStyle( "RL Background" ) );
}
EditorGUILayout.EndVertical();
}
Why does GUIStyle have a difference about size? In case of "RL Background", how can I control the size like "default box"?
Answer by Bunny83 · Dec 02, 2017 at 01:31 PM
A GUIStyle has a setting called stretchHeight and stretchWidth which controls if the element should use as much space as available. The way the layout system works is that during the layout event Unity collects information about all elements. The elements which have a fixedWidth / Height are considered first. Their values are all added up and subtracted from the available space. The remaining space would usually be distributed between all expanding elements within the same layout group. However the distribution depends on the element sizes.
Instead of creating a new GUIStyle for every possibility one can add one or multiple GUILayoutOptions to almost all elements. There's a "params" array at the end of most control methods which allows that. The available GUILayoutOptions are:
Those options can be added to the actual call to the control method to overwrite certain the settings of the used GUIStyle.
Also note that there's the FlexibleSpace control. It will eat up any "left over space" which makes expandable elements as small as possible to fit all content.
You may want to have a look at my IMGUI CrashCourse. Unfortunately the latest changes on UnityAnswers renders the post like a wall of text. Paragraph spaces and bulletpoint indention has been removed which makes it look kinda messy.
Also note that when using the layout system in an EditorWindow or in a custom inspector the available space is usually the whole editor window to begin with. However if you use it in a Game the available space is not setup at all. The overall space grows as needed from the top left up to the screen dimensions. To actually stretch across the screen you would need to create an area that covers the entire screen (or the area you want) using BeginArea / EndArea
Just as example, the default Button style does not stretch it's height (it has a fixedHeight) but it does stretch it's width.
Thank you for amazing answer!
I have never seen stretchHeight and stretchWidth.
var style = new GUIStyle( "RL Background" );
style.stretchHeight = false;
style.stretchWidth = false;
I can control size of GUILayout as desired:)