How to scale my GUI.Label with the screensize?

Hey, I am making a mobile Game. So it is for phones and tablets. The Problem is that my GUI.Labels are very small on a Tablet! How do I scale them with the Screensize?

    void OnGUI()
    {
        guiStyle.fontSize = 60;
        GUI.Label(new Rect(105, 22, 100, 100), score.ToString(), guiStyle);
        GUI.Label(new Rect(205, 22, 100, 100), hiScore.ToString(), guiStyle);
        if (showScoreInTheMiddle == true) {
            GUI.Label(new Rect(515, 290, 100, 100), score.ToString(), guiStyle);
        }
        if (showHealthOnScreen == true) {
            GUI.Label(new Rect(105, 22, 100, 100), pScript.health.ToString(), guiStyle);
            GUI.Label(new Rect(105, 22, 100, 100), upgradePoints.ToString(), guiStyle);
        }
    }

make all your values a fraction of Screen.width and Screen.height.

1 Like

Why on earth are you using OnGui? Feel like I’m back in 2011… but anyways …

You have two options:

  1. Apply a style which scales font size based on screen size
public class GuiTest : MonoBehaviour {
    Vector2 nativeSize = new Vector2(640, 480);
    void OnGUI() {
        GUIStyle style = new GUIStyle ();
        style.fontSize = (int)(20.0f * ((float)Screen.width / (float)nativeSize.x));
        // Your code here
        GUI.Label(new Rect(105, 22, 100, 100), "Score", style); 
        GUI.Label(new Rect(205, 22, 100, 100), "HiScore".ToString(), style);
    }
}
  1. Use a matrix to transform GUI…
public class GuiTest :  MonoBehaviour {
    Vector2 nativeSize = new Vector2(640, 480);
    void OnGUI() {
        Vector3 scale = new Vector3 (Screen.width / nativeSize.x, Screen.height / nativeSize.y, 1.0f);
        GUI.matrix = Matrix4x4.TRS (new Vector3(0, 0, 0), Quaternion.identity, scale);
        // Your code here
        GUI.Label(new Rect(105, 22, 100, 100), "Score"); 
        GUI.Label(new Rect(205, 22, 100, 100), "HiScore".ToString());
    }
}
7 Likes

This is still relevant as it’s used in 3rd party tools like ngui still.