I am creating a guiText element and attaching it through script and want to set the font to something other than the default.
I am having difficulty figuring out how to get or access a font type. For example:
textGO = new GameObject("bub_txt");
var textElement : GUIText = textGO.AddComponent("GUIText");
textElement.font = new Font("Chalkboard"); // I know this doesn't work
textElement.text = "HERE IS SOME TEXT";
So the above code for getting a font I know doesn’t work but I am totally stuck on how to do this. Could someone please provide some insight?
Thanks!
– Clint
You can’t just construct a new Font at runtime (not using unity at least). The easiest solution is probably to make a Font manager and get fonts through it.
using UnityEngine;
using System.Collections;
public class FontManager {
public Font[] fonts;
private FontManager instance;
public FontManager get {
get {
return instance;
}
}
public void Awake() {
instance = this;
}
public Font GetFont(string fontName) {
foreach (Font font in fonts)
if (font.name == fontName)
return font;
return null;
}
}
Make a gameObject with this scrip in you scene and drag your fonts into the array. These can be assesed from script by typing:
textElement.font = FontManager.get.GetFont("Chalkboard");
Ofcource, if you just need a single font, this might be overkill :-).
Thanks Talzor!
I was hoping not to have a manager but it will work well.
Thanks again!
– Clint
Unity 1.6 has support for Resources now, so if you want to grab something by path name now, you can very easily do that using the Resources class. Anything in the Resources folder can be accessed by it’s path. Including prefabs, fonts, materials, sounds or anything really.
http://unity3d.com/Documentation/ScriptReference/Resources.Load.html
1 Like
textElement.font = Resources.Load("Chalkboard");
And place Chalkboard.ttf inside the folder “Assets/Resources”
Cool! Thanks a lot Jo!
I’ll give that way a shot.
Regards,
– Clint
It doesn’t happen…….It simply says “Cannot implicitly convert type UnityEngine.Object' to
UnityEngine.Font’. An explicit conversion exists (are you missing a cast?)”
textElement.font = (Font)Resources.Load("chalkBoard");