I’m learning about making custom windows in Unity but recently I’ve run into the following problem and I don’t know how to fix it. It may be a bug in Unity.
To place any element (a label for example) in the center of a window I follow the logic of “Screen.width / 2”, but when I scale the editor in the preferences it gets all messed up.
Does anyone know why this happens?
How can I place things in the place I want if when I scale the ui everything gets messed up?
I attach some images and the code so you can try it by yourself.
using UnityEngine;
using UnityEditor;
public class MyWindow : EditorWindow
{
[MenuItem("Window/My Window")]
public static void ShowWindow() => GetWindow(typeof(MyWindow));
private void OnGUI()
{
Vector2 position = new Vector2(Screen.width / 2, 0f);
Vector2 size = new Vector2(40f, 20f);
Rect rect = new Rect(position, size);
GUI.Label(rect, "Label");
}
}
I’m not sure how that scaling works internally, but it makes sense that if you don’t account for it and draw the element in the same position, that it’s no longer the proper position.
Thank you, I was able to solve the problem!
Instead of using “Screen.width / 2” I have to use “position.width / 2”.
This is how the code looks like:
using UnityEngine;
using UnityEditor;
public class MyWindow : EditorWindow
{
[MenuItem("Window/My Window")]
public static void ShowWindow() => GetWindow(typeof(MyWindow));
private void OnGUI()
{
Vector2 p = new Vector2(position.width / 2, 0f);
Vector2 s = new Vector2(40f, 20f);
Rect r = new Rect(p, s);
GUI.Label(r, "Label");
}
}
Thanks for following up. Just beware that you are not in the PRECISE center. The “position” refers to the top left corner of the Rect, but with a small size like 40x20 it is almost unnoticeable.
Try making a larger-sized Rect and you will see what I mean instantly.
{
Vector2 p = new Vector2(position.width / 2, 0f);
Vector2 s = new Vector2(110f, 20f);
Rect r = new Rect(p, s);
GUI.Label(r, "A BIGGER LABEL");
}
Obviously you just need to subtract the s.width / 2 from position.x at some point.
And obviously if the text doesn’t fill the rect, it doesn’t matter anyway because it won’t be centered!
I personally like this construct:
{
Rect r = new Rect( 0, 0, 100, 20); // size
r.center = new Vector2( position.width / 2, r.height / 2);
GUI.Label(r, "A center top label");
}
I too have had issues with element placement if using editor gui scaling. Like @GroZZleR said, instead of using GUI you could also use automatic layout. I’ve used something like this earlier:
private void OnGUI()
{
// Center Vertically
GUILayout.FlexibleSpace();
// Horizontally centered
using (var l = new EditorGUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
GUILayout.Button("Centered!", GUI.skin.box);
GUILayout.FlexibleSpace();
}
GUILayout.FlexibleSpace();
}