1
\$\begingroup\$

Specifically it's Font.CreateDynamicFontFromOSFont(), use this script attached to an empty GameObject in the scene.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestFontTexture : MonoBehaviour {

    void Start () 
    {
        var font = Font.CreateDynamicFontFromOSFont("Consolas", 12);        
        font.RequestCharactersInTexture("HelloWorld", 20);
        SaveTexture2PNG("./fontTexture.png", (Texture2D)font.material.mainTexture);
    }

    void Update () 
    {

    }

    void SaveTexture2PNG(string path, Texture2D tex)
    {
        byte[] bytes = tex.EncodeToPNG();
        System.IO.File.WriteAllBytes(path, bytes);
    }
}

After click play it should create a fontTexture.png file containing character glyphs in the Assets folder, but only in editor though. In the built game it just created a completely black image.

Since it's OS concerned, I'm using Windows 7 with font Consolas installed and Unity 5.6.5f.

How to make it work in a built game?

\$\endgroup\$
3
  • \$\begingroup\$ I would not recommend to use CreateDynamicFontFromOSFont. Your game won't work if the player doesn't have that font installed. Different operating systems have different fonts, so you will unnecessarily limit the platforms you can release for. It is usually better to add any fonts you want to use as assets. But keep the license conditions in mind. Not all fonts included in Windows allow redistribution. \$\endgroup\$
    – Philipp
    Commented Aug 29, 2018 at 7:57
  • \$\begingroup\$ @Philipp It should be released only in Windows and Consolas is installed by default I think. But thanks for mentioning the license stuff. \$\endgroup\$
    – Arxz
    Commented Aug 29, 2018 at 9:54
  • \$\begingroup\$ Have you tried adding a delay between creating the font, populating it with characters, and saving it? It's possible that some of these operations are queued and execute later in the frame rather than instantaneously. \$\endgroup\$
    – DMGregory
    Commented Aug 29, 2018 at 11:53

1 Answer 1

1
\$\begingroup\$

Just solved, it's about the readability of font.material.mainTexture.

In the editor there's no warning or error, and it's readable, but not in the built game.

Try to create the font by Resources.Load() instead of procedurally creating it from script, it'll pop up error when accessing font.material.mainTexture saying it's unreadable.

Using the script from https://support.unity3d.com/hc/en-us/articles/206486626-How-can-I-get-pixels-from-unreadable-textures-

and it works fine.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .