Cache Rect in Start()

Hi,
is there any sense in caching Rects which are used in the OnGUI method on application start?

I know Rect is a struct and structs are stored on the stack, isn’t it?
But I feel unconfortable calling new Rect in OnGUI() several times per frame…

Same with Screen.width/height. Should I call it, everytime I need it, or store the value in an screenHeight/Width variable? Senese/benefites?

How do you do it?

From my perspective, it depends on your performance needs. If you’re trying to squeeze out every bit of CPU, cache everything possible since, as you wrote, Unity calls OnGUI multiple times per frame. Regardless of stack or heap, constructing a Rect is extra overhead.

But if it’s, say, a main menu where the game is otherwise paused, there’s no sense adding the extra complexity (and extra maintenance and extra potential for bugs) by caching everything. However, in this case, I’d disable the component containing the main menu’s OnGUI method when the menu isn’t active. Unity incurs a fairly steep overhead to set up an OnGUI call, even if it just checks a bool and exits immediately.

If rects are static, you can define them as private properties:

private Rect _myRect = new Rect(0, 0, 100, 50);

If your rects depend on Screen dimensions (change) you should compare the old and the new screen size in each frame and take action on change. However, try to do it once per frame, not per component :slight_smile:

(although I believe Unity should cache the size internally, but I’m not sure)

My way of doing it is having the central place where the screen size is checked once per Update. Then I can read this value (width + height) from my code. The more important, I can subscribe to a signal firing when the screen size changes.

You could check the SystemManager class of my framework.