Hello everyOne!
I need to display a text and a button next to it.
I might send the GUI.Label text dynamically and don’t know the accurate size.
For now I have placed the label at 0 with a padding, and the button far away at Screen.width/2 , so that for a long word/words they don’t override each other.
Of course both have same height…
Is there a method that I can place the button just after the GUI.Label, and I seperate them with only padding.
thanks in advance
You could try to get your labelText.Length, but I think CalcSize works out better in the end. If you happen to have a background box behind your label, CalcSize will keep the length accurate even if certain characters take more space than others. Below is a quick example:
public string labelTextHere = "Edit in Inspector";
private int leftPosition = Screen.width / 2;
private int topPosition = Screen.height / 2;
private int boxHeight = 20;
private float newBoxWidth;
private GUIStyle myStyle = new GUIStyle();
Vector2 sizeOfLabel;
void Start() {
myStyle.alignment = TextAnchor.MiddleCenter;
//any other styles
}
void OnGUI() {
//Calculates the size of your label text with myStyle
sizeOfLabel = myStyle.CalcSize(new GUIContent(labelTextHere));
//sizeOfLabel.x will get the length. +6 can be adjusted for padding
newBoxWidth = sizeOfLabel.x + 6;
//The background box behind the label, just for the example.
GUI.Box(new Rect(leftPosition - newBoxWidth / 2, topPosition + 15, newBoxWidth, boxHeight), "");
//The label text, this example is centered
GUI.Label(new Rect(leftPosition - newBoxWidth / 2, topPosition + 15, newBoxWidth, boxHeight), labelTextHere, myStyle);
//The button, drawn to the right of wherever the label ends.
GUI.Button(new Rect(leftPosition + newBoxWidth / 2, topPosition + 15, 25, boxHeight), "");
I think these days this is the better answer:
http://docs.unity3d.com/ScriptReference/EditorGUILayout.PrefixLabel.html