- Home /
How to find a font via script?
Another one that should be really easy, but which is mysteriously elusive to me. Okay, so I have imported a custom font through the TTF Importer, which was very easy. Now how do I reference that font through code in order to actually tie it to some custom GUIStyles, etc? GameObject.Find nor GetComponent seem to be the right thing.
Answer by Eric5h5 · Mar 17, 2010 at 12:02 AM
var someFont : Font;
var style : GUIStyle;
style.font = someFont;
This is just creating an empty font, yes? Unless I am misunderstanding something. I want to find a reference to an existing font that I have already imported through the Unity editor -- but I want to find access to it in code, so that I can do essentially what you are describing in your second two lines. That part is straightforward, but on that first line of your code I want to find a reference to an existing font rather than declaring a new, empty one.
@x4000: It's not creating a font, it's creating a public variable that you use to reference the font. (I forgot to mention the part about those being public variables. ;) ) You can drag the font you want onto the public variable.
Ah, okay -- the public variable with dragging through the interface solves it. That's good enough for making an ongoing reference I can then use later. Thanks!
Answer by Jaap Kreijkamp · Mar 16, 2010 at 11:48 PM
Place the font in the Resources
folder and use Resources.Load
to load assets dynamically.
That is really helpful, actually, but not quite what I am looking to do. In this case I already have the font imported just fine into the game, but I am looking to access the imported version of it that I can then render. In other words, it is called "Regular" as a font. But, I can't seem to set a Name for it in the editor that I can see (a lot of grayed out controls), and I don't see any methods on the Font class for finding a reference to an existing font. I see how GameObjects can be looked up, but that does not seem to work for fonts...
Answer by cedw032 · Jun 24, 2013 at 05:52 AM
var font:Font = Instantiate( Font.FindObjectsOfTypeAll( Font )[0] );
Font.FindObjectsOfTypeAll()
is now deprecated. As of Unity 5, the C# equivalent of the above code is as follows: Font font = Instantiate (Resources.FindObjectsOfTypeAll (typeof (Font))[0]) as Font;