Unity Editor: Pseudo-"Media Queries" in IMGUI

Even with plenty of UI systems out there nowadays and a new Editor UI system adapting things like stylesheets from Web-Development on the horizon, there's still a need for the "legacy" Intermediate GUI (IMGUI) system in Unity (and I hope that they aren't going to replace it in the future, because once you get the hang of it, it becomes a valuable tool to display information on the screen or create whole extensions for Unity with).

Because most editor windows are meant to be dockable in Unity's neatly modular GUI, you have to design the content of your windows with responsibility in mind. While it's still a good idea to limit the minimum screen size of your window to at least a few hundred pixels/points, being too restrictive by limiting the size to the ideal window size might hurt the user experience.

As such, it’s a good idea to prevent your content from being displayed too narrowly when the window is being downsized and for that we can learn from established solutions in the field of Web-Design, namely media queries (a.k.a. adjusting content to the size of the window, not the other way around, to achieve responsive layouts and prevent cutting of content when the window gets too small).

To achieve a different styling behavior depending on the window size (analog to media-queries in Web-Design) you have to:

  • define a breakpoint, at which size the styling should change

  • check the current position size against the breakpoint and store it in a boolean variable

  • use that variable where you want your behavior to change and

So actually pretty straight-forward. Let's look at a simple example:

private float breakPoint = 900f;
private bool compactView;

private void OnGUI()
  //check whether the current window's width is smaller than the defined break-point
  compactView = position.width < breakPoint;

  //setup-bar offset
  GUILayout.Space(compactView ? 64f : 34f);

  float setupWidth = compactView ? lAreaRect.width : lAreaHalf;

  if (GUILayout.Button("Loooooooooooooooong Button", GUILayout.MaxWidth(setupWidth))) {
    Debug.Log("Clicked the long button");

Here we check whether the current width of position (the screen-dimensions of the current window) against our specified breakpoint and show a more "compact view" if it's smaller than that.

Since OnGUI() runs in the Editor on every interaction with the window, it's the ideal place for adjusting the content based on the current window width or height. You can also have multiple breakpoints, but that just might make it unnecessarily complex.

Fri May 08 2020