Loading a font at runtime?

Hello there,

how would I load a font at runtime? What I wanna do is a simple main menu with text-buttons and I would like to avoid having to set the font manually in the inspector but instead load it automatically. I’ve been trying the following, but I always get a wrong font (looks like the standard arial) and the background is all messed up…

using UnityEngine;
using UnityEditor;


class MainMenu : MonoBehaviour
{
    public GUIStyle style = new GUIStyle();
    public int cx = 0;
    public int cy = 0;

    public int btnWidth = 120;
    public int btnHeight = 35;

    public void Start()
    {
        style.normal.background = new Texture2D(120, 35);
        style.hover.background = new Texture2D(120, 35);
        style.normal.textColor = new Color(0f, 0f, 0f);
        style.hover.textColor = new Color(0f, 0f, 128f);

        // the following seems to (silently) fail
        style.font = (Font)Resources.Load("BADABB__"); // badaboom font
        style.fontSize = 34;
    }

    public void OnGUI()
    {
        cx = (Screen.width / 2) - (btnWidth / 2);
        cy = Screen.height / 2;
 
        if (GUI.Button(GetRect(-87.5f), "New Game", style)) { Application.LoadLevel("Level1.0"); }
        if (GUI.Button(GetRect(-52.5f), "Load Game", style)) { Application.LoadLevel("Load Menu"); }
        if (GUI.Button(GetRect(-17.5f), "Save Game", style)) { Application.LoadLevel("Save Menu"); }
        if (GUI.Button(GetRect(17.5f), "Options", style)) { print("this takes you to the options menu"); }
        if (GUI.Button(GetRect(52.5f), "Exit", style)) { print("this exits the game"); }
    }

    public Rect GetRect(float yOffset) { return new Rect(cx, cy + yOffset, btnWidth, btnHeight); }
}

I’m totally new to coding in Unity, but not to coding in general. What would be correct way to do it in Unity?

Greetz,

Tox

Is the font located in a folder named ‘Resources’?

Otherwise it won’t load.

Thanks a lot, that solved the problem. I expected Unity to throw an error if it’s unable to find a file.

nope
but you can always check for != null after loading to know if it failed

True. Is this some special case for the Resources.load() function or does Unity never report missing files?

it does not throw exceptions normally on functions that “find” stuff, it will return null to signal that it wasn’t found (exception bring some serious overhead with them)

ah, ok. thx. I’m currently mostly developing in AS3, so I’m used to errors being thrown for everything. :wink:

Unity will throw error too: NullReferenceException if you use such null initialized variables :wink:

In case of the font you were just lucky that there is a default font active that will jump in if none is specified

TonyD Thanks a lot it helped me out too.