- Home /
Screen height and width confusion
I dont really get why this doesn't work:
GUI.Box(new Rect(Screen.height/2, Screen.width/2, 100, 100),"Box in the middle");
The way I understand this, the code should place a 100*100 box with its left top side directly in the middle of the game. What i get is a box that is placed almost in the bottom and a bit to the left. And if i maximize on play the box is not even there (guessing its outside the camera area).
Am i missing something big, or is there anotother way to get a position by using Screen.height and Screen.Width? i want my box to scale to different screens, which is why i am doing it this way
Answer by Xarbrough · Feb 25, 2018 at 02:05 PM
You need to flip height and width like this and also offset the position by half the width (because the box pivot is at a corner, not the center):
using UnityEngine;
public class Test : MonoBehaviour
{
void OnGUI()
{
Rect rect = new Rect(Screen.width / 2f, Screen.height / 2f, 120f, 60f);
rect.x -= rect.width / 2f;
rect.y -= rect.height / 2f;
GUI.Box(rect, "Box in the middle");
}
}
Maybe you can think of it like this as well:
Vector2 size = new Vector2(120f, 60f);
Vector2 position = new Vector2(
x: Screen.width / 2f - size.x / 2f,
y: Screen.height / 2f - size.y / 2f);
GUI.Box(new Rect(position, size), "Box in the middle");
Also be aware that the this is the legacy GUI system and is replaced by the new Unity UI system. The new system makes layouting much easier because it uses anchors and layout groups which do the work for you. It also has better performance than the legacy immediate mode GUI.
Scaling in the legacy GUI system was more of a hassle. If you want your box to stay the same size across multiple resolutions, you either have to calculate the position and size of every element manually by factoring in the screen size or edit the GUI.matrix like this:
Vector2 referenceResolution = new Vector2(1920f, 1080f);
Vector3 scaling = new Vector3(
x: Screen.width / referenceResolution.x,
y: Screen.height / referenceResolution.y,
z: 1f);
GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, scaling);
Vector2 size = new Vector2(1920f - 50f, 260f);
Vector2 position = new Vector2(Screen.width / 2f, Screen.height / 2f);
position -= size / 2f;
GUIStyle style = new GUIStyle(GUI.skin.box);
style.fontSize = 30;
GUI.Box(new Rect(position, size), "Box in the middle", style);
This will ensure that on 16:9 screens, the box fills the screen. But, you can also see that it's a difficult topic, because its still strongly connected to your reference resolution, so it doesn't adapt between portrait and landscape resolution, etc. All of these problems are solved by the new UI system, which was introduced with Unity 4.6, though.
Note that the Rect now has a center property which can be set as well. So you can simply do
Rect rect = new Rect(0 , 0, 120f, 60f);
rect.center = new Vector2(Screen.width / 2f, Screen.height / 2f);
GUI.Box(rect, "Box in the middle");