- Home /
Autosized GUI element in an arbitrary location
Basically what I want is an autosized tooltip. What I've got so far is GUILayout.Box() that creates an autosized box with text inside it, but places it in the top left corner.
The only way I see to move it, is by putting it inside a GUILayout.BeginArea() / GUILayout.EndArea() block, but the Area cannot be autosized - I have to specify a Rect which destroys the whole point.
I even tried specifying an unreasonably large Rect for the Area, but once the Box is inside an Area it stretches horizontally to however big the Area is.
Answer by robertbu · May 08, 2014 at 03:10 PM
Here is an example of using GUI (not GUILayout), to autosize a box. Both 'text' and 'pos' can be changed at runtime, and the box will resize and/or reposition.
#pragma strict
var pos = Vector2(100,100);
var text = "Here is some text";
private var _text = "";
private var _pos = Vector3.zero;
private var rect : Rect;
function OnGUI() {
if (_text != text || _pos != pos)
Recalc();
GUI.Box(rect, text);
}
function Recalc() {
_text = text;
_pos = pos;
var size = GUI.skin.GetStyle("Box").CalcSize(new GUIContent(text));
rect.x = pos.x;
rect.y = pos.y;
rect.width = size.x;
rect.height = size.y;
}
Answer by gfallasc · May 08, 2014 at 03:34 PM
This is some confusing, but If you're using the GUILayout
components, you should always wrap them into a parent or desired area. You could create a dynamic area (`Rect`) using the Screen.height
and Screen.width
values, and then add components inside. You could use the orientation GUILayout.BegintHorizontal
and GUILayout.EndHorizontal
(there's also a Vertical block) and if you want to 'anchor' a component inside a box you could use the GUILayout.FlexibleSpace()
method that will expand a blank space, according to the orientation, being relative if you add before/after the component, and if you want to the components don't expand you could use the GUILayout.ExpandWidth
or GUILayout.ExpandHeight
options, by default both are true: here's a example: GUILayout.Button("Button", GUILayout.ExpandWidth (false));
Hope it helps you.