If you have experienced your Unity3D GUI text turning to scrambled gibberish on mobile (at least as of Unity3D 4.3.4), you haven’t made an error in your code. Currently, Unity3D seems to have problems with maintaining the display of text on (at least Android) phones. The code runs as expected on a desktop though.
The error plays out like this: the app starts correctly, however, once the GUI needs to be resized, say because a GUI label has some new text to display, everything breaks.
The easiest solution I’ve discovered is to place the text sizing / GUI scaling code in the Start() function, and have those measurements remain static during the app’s run.
If you want to know how to get the width and height of text in Unity3D, it’s like so…
Firstly declare a GUIStyle for the intended text and GUI component(s), and at least one Rect per GUI component for example:
1 2 3 |
var buttonStyle : GUIStyle; var buttonRect : Rect; |
Next, we’ll use that GUIStyle to determine the size of some text. The code lines below set a Vector2, whose x and y values can be used to set the width and length of a GUI component. In this case, we apply the measurements to the variable buttonRect, which we can then apply as the measurements for a component later on.
The two lines below would go in the Start() function on mobile, but both lines can also go in the OnGUI() function for desktops.
1 2 3 |
var sizeOfText : Vector2 = buttonStyle.CalcSize(new GUIContent("Example text")); buttonRect = new Rect(10, 10, sizeOfText.x + 10, sizeOfText.y + 10); |
You’ll need to use those measurements together with the exact GUIStyle which was used to generate them – else you’ll get scale mismatches.
The line below makes correct use of the GUIStyle and Vector2, and would go on the OnGUI() function.
1 2 3 |
if(GUI.Button(buttonRect, "Example text", buttonStyle)){ } |
Pingback: Unity3D mobile text GUI error | VISUALS+CODE