How do I find font by passing a string?

Hi guys,

I have a few GUIText objects that have a set font. I also have an @2x version of the same font for retina displays (the title of the font is @2x). The following code is what I’ve written so far, even though it results in an error:

oneUsePrice.font = + "@2x";
fiveUsePrice.font = + "@2x";
tenUsePrice.font = + "@2x";
twentyUsePrice.font = + "@2x";

Because it assigns strings to a font value, it results in the following error:

error CS0029: Cannot implicitly convert type `string' to `UnityEngine.Font'

So there needs to be a way to find the font with the name specified on the right side of each assignment, then set the left side to that font. Example in partial pseudocode:

oneUsePrice.font = Font.FontWithName( + "@2x");
fiveUsePrice.font = Font.FontWithName( + "@2x");
tenUsePrice.font = Font.FontWithName( + "@2x");
twentyUsePrice.font = Font.FontWithName( + "@2x");

For the record, the reason for wanting to use string parsing to solve this problem (as opposed to setting a Font class variable and using it to swap the @2x font) is because I want to have code that can be reused even in cases where different GUIText objects have different fonts.

Thanks in advance,


Like all assets in Unity, fonts can be accessed either by dragging them into a variable on an object in their hierarchy, or by using Resources.Load. Otherwise, Unity would have no way to know which of your assets you actually want in your game, and in what Scene you want them.