Unity3D: Manage GUI elements for any aspect ratios (2D 3D)
23rd Aug 2013
I do know that lots of discussions have happened on this topic and most of them are resolved, Recently, I've came across a large game project, which had lots of GUI elements to be drawn at on screen on different times. I somehow managed to draw it, but there were a big issue when switch the game to different aspect ratios. And I've found out a real simple solution to solve this problem and I'd like to share this simple idea so that it may help some people. This method will work for almost all platform. No matter what the player's screen aspect ratios are:
Step 1 : Divide your screen as 10x10 grids (Make a rough sketch or something like that to figure out where do you want to put your GUI elements on screen)
I'm not good at MS Paint 😅
And write your script as follows
public class MyClass : MonoBehavior {
private float dx, dy;
private Rect redRect,
blueRect,
orangeRect;
void Start() {
SetGUIAspectRatio();
}
void SetGUIAspectRatio() {
dx = Screen.width / 10;
dy = Screen.height / 10;
redRect = new Rect(2f * dx, 4f * dy, 2f * dx, 2f * dy);
blueRect = new Rect(7f * dx, 2f * dy, 2f * dx, 2f * dy);
redRect = new Rect(4.5f * dx, 7f * dy, dx, 2f * dy);
}
void OnGUI() {
GUI.Button(redRect, "Red rect");
GUI.Button(blueRect, "Blue rect");
GUI.Button(orangeRect, "Orange rect");
}
}
Resizable screen
If you're having a Resizable screen, the Above code will only work according to the Startup screen size. To solve this issue you could do a small edit in the above script.
public class MyClass : MonoBehavior {
private float dx, dy;
private Rect redRect,
blueRect,
orangeRect;
void SetGUIAspectRatio() {
dx = Screen.width / 10;
dy = Screen.height / 10;
redRect = new Rect(2f * dx, 4f * dy, 2f * dx, 2f * dy);
blueRect = new Rect(7f * dx, 2f * dy, 2f * dx, 2f * dy);
redRect = new Rect(4.5f * dx, 7f * dy, dx, 2f * dy);
}
void OnGUI() {
//Call the SetGUIAspectRatio() function just before GUI button definitions
SetGUIAspectRatio();
GUI.Button(redRect, "Red rect");
GUI.Button(blueRect, "Blue rect");
GUI.Button(orangeRect, "Orange rect");
}
}