- Home /
GUI.Label font size scale - using GUISkin
I've read lots about using Matrix4x4 to scale GUI elements and it has been very useful. I now have a problem where I am using Camera.WorldToScreenPoint to position a label over a "sprite" game object, but the font size appears small on mobile devices.
If I use the Matrix to scale, the font size scales well, but the location is skewed as "go.pos.x" gets adjusted by the scale (I assume?).
Is there a way to target just the font size when it comes to the scale?
void OnGUI(){
//GUI.matrix = Matrix4x4.TRS (Vector3.zero, Quaternion.identity, new Vector3(scale.x, scale.y, 1));
GUI.skin = skin;
Level[] allLevels = FindObjectsOfType<Level>();
foreach(Level l in allLevels){
Vector3 pos = Camera.main.WorldToScreenPoint(l.transform.position);
GUI.Label (new Rect(pos.x-10, Screen.height- pos.y-15, 50,50), l.levelNum.ToString ());
}
}
Current code - matrix commented to ensure the position is fine when not scaling (it is).
Any clues?
Thanks
Answer by zharik86 · Aug 04, 2014 at 07:34 AM
If you want to do it by means of the OnGUI function, it is best of all to make in your GUISkin one more style for Label. And name this style, for example, is myLabelLevel. Further, you will need to set correctly type size for your style. Better to do all this as Awake () or Start (). I wrote an example below:
public GUISkin skin = null; //reference for your skin
void Start() {
//For example, for landscape orientation size font is 30 for Screen.width=1920, than
skin.GetStyle("myLabelLevel").fontSize = (int)(30.0f * Screen.width / 1920.0f);
}
void OnGUI() {
GUI.skin = skin;
Level[] allLevels = FindObjectsOfType<Level>();
foreach(Level l in allLevels) {
Vector3 pos = Camera.main.WorldToScreenPoint(l.transform.position);
GUI.Label (new Rect(pos.x-10, Screen.height- pos.y-15, 50,50), l.levelNum.ToString (), "myLabelStyle"); //Use custom style
}
}
I hope that it will help you.
Thanks Zharik, your solution worked a charm! The use of an in-line scale adjustment also helped me resolve an issue with slight amendments to placement (left a few pixels, etc.) - so top props from me! :)