- Home /
EditorGUILayout.LabelField not centered properly
I have created an editor window script to create an editor window. I have a Rect variable headerRect with the following properties:
headerRect.x = 0f;
headerRect.y = 0f;
headerRect.width = Screen.width;
headerRect.height = 50f;
GUI.DrawTexture(headerRect, headerRectTexture);
Here is the function that creates a label in the headerRect section.
private void DrawHeaderSection() // Draws the Header Section
{
GUILayout.BeginArea(headerRect);
EditorGUILayout.LabelField("CHARACTER EDITOR", guiSkin.GetStyle("Header"));
GUILayout.EndArea();
}
The GUISkin has a style called "Header" and it mentions that the alignment is MiddleCenter but still the alignment is not proper. Rather, it seems that the text is starting from the middle of the width. The following image will demonstrate the problem.
How do I properly align the label to the centre?
Answer by SwastikBhattacharyya · Mar 29, 2020 at 07:24 AM
The Solution
Change the Fixed Width field in your GUISkin file
Enter the value of your screen width to that field ie. if the width of the headerRect is 600 then write 600 in the Fixed Width field in the inspector.
Change the Fixed Width of your style through Code
Change the DrawHeaderSection() function to this:
private void DrawHeaderSection() // Draws the Header Section
{
GUILayout.BeginArea(headerRect);
guiSkin.GetStyle("Header").fixedWidth = 600;
EditorGUILayout.LabelField("CHARACTER EDITOR", guiSkin.GetStyle("Header"));
GUILayout.EndArea();
}
Add the following line before drawing the label
guiSkin.GetStyle("Header").fixedWidth = 600;
NOTE: You might be thinking why did I put 600 instead of Screen.width. It's because Screen.width was returning 750 instead of 600 which is the wrong value.
Your answer
Follow this Question
Related Questions
Is there a way to get all editable fields of a component in a script? 2 Answers
How to get Event.KeyboardEvent from non-focused EditorWindow? 0 Answers
Populating object fields in a loop - editor scripting 1 Answer
Saving a variable from an editor script into something like a gamemanager script? 0 Answers