Optimizing OnGUI

Hi.
I’m trying to see if it’s possible somehow to optimize the OnGUI function in my project.
If I make a gui layout label like this:

GUILayout.Label(PlayerPrefs.GetFloat("Pl1_Score").ToString("N0", new System.Globalization.CultureInfo("sv-SE")), GUILayout.Width(Screen.width / 3.5f));

Then I tell it to get the playerprefs, convert it to string and set the width.

Wouldn’t it be better to fill a string like this:

private String newStringIJustMade = PlayerPrefs.GetFloat("Pl1_Score").ToString("N0", new System.Globalization.CultureInfo("sv-SE"));

and then just write

GUILayout.Label(newStringIJustMade, GUILayout.Width(Screen.width / 3.5f));

and even better, make the last part a variable as well which you declare in Awake()

private float GuiWidth;
GUIWidth = Screen.width / 3.5f;

and writing:

GUILayout.Label(newStringIJustMade, GUILayout.Width(GUIWidth));

Hopefully that made sense.
Would this make any bigger difference?

I have a lot of labels and buttons that work like this and would like to try and optimize it as much as possible.
But on the other hand I heard that making a variable in the top of the code is a bad idea and will cause performance issues if you use to many…

Thanks for reading.

Hi,

I wouldn’t use OnGUI at all, specially if you are deploying on mobile devices. OnGUI is heavy and based on really old code so you can’t optimize it. In Unity 4.6 there will be a new GUI library that is much more optimized, so until then, use some other library.

I use NGui, but that costs, so if you want a cheaper way you can use ezgui.