Bulletproof way to do resolution independant GUI scaling?

I’m having a really hard time getting GUI scaling to work. I’m working on a base resolution of windowed 1024x768 and I find that whenever I change the resolution all of my GUI elements get moved around and it pretty much breaks my game. I want to give users the ability to run at whatever resolution they want so this is a big issue.

I’ve searched around and I’ve seen a lot of solutions involving changing the GUI Matrix in the OnGUI function but my game just uses GUITextures with scripts attached, so OnGUI never gets called.

Is there any solution?

An alternative way to scale GUI elements automatically is to add this snippet of code to the top of all of your OnGUI() functions, and then create your boxes in native resolution pixel numbers. The GUI.matrix setup below will scale everything to look the same on all machines

var native_width : float = 1920;
var native_height : float = 1080;

function OnGUI ()
{
    //set up scaling
    var rx : float = Screen.width / native_width;
    var ry : float = Screen.height / native_height;
    GUI.matrix = Matrix4x4.TRS (Vector3(0, 0, 0), Quaternion.identity, Vector3 (rx, ry, 1)); 

    //now create your GUI normally, as if you were in your native resolution
    //The GUI.matrix will scale everything automatically.

    //example
    GUI.Box(  Rect(810, 490, 300, 100)  , "Hello World!");

}

Normally I’m against handing out free code like this, but GUI.matrix is complex {think 200-level college Math course complex} and it took me about 15 minutes of searching to find.

I wrote the GUI scaling code for our app the first day I used Unity.

We base our entire GUI on the height of the window.

We check the window height at the beginning of OnGUI. That value is compared to the optimized height (768) to determine the scale ratio.

From that point on the resulting ratio is applied to the position and size of the rectangles of all GUI elements.

I’ll admit that I probably didn’t do it the most efficient way possible, but we’ve never had to revisit the scaling code since day 1 and our app looks the same on all resolutions.

We even scale our fonts for standalone and web builds.