Files
megakoop/Game/Scripts/UI/FontAssetPreloader.cs
2025-10-05 18:21:16 +02:00

42 lines
1.5 KiB
C#

using UnityEngine;
using UnityEngine.TextCore.Text;
namespace MegaKoop.Game.UI
{
/// <summary>
/// Preloads required characters into dynamic font atlases on the main thread to avoid runtime race conditions.
/// Attach once to a bootstrap GameObject and assign all UI font assets used by UITK.
/// </summary>
public sealed class FontAssetPreloader : MonoBehaviour
{
[SerializeField] private FontAsset[] fontAssets;
[SerializeField, TextArea(1, 4)] private string charactersToPreload = "…•-";
private System.Collections.IEnumerator Start()
{
if (fontAssets == null || fontAssets.Length == 0)
{
yield break;
}
// Wait one frame to ensure the scene finished loading on the main thread.
yield return null;
foreach (FontAsset asset in fontAssets)
{
if (asset == null)
{
continue;
}
// Try to add characters that are commonly generated at runtime (ellipsis, bullets, dashes, etc.).
bool allAdded = asset.TryAddCharacters(charactersToPreload, out string missingCharacters);
if (!allAdded && !string.IsNullOrEmpty(missingCharacters))
{
Debug.LogWarning($"[FontAssetPreloader] Missing glyphs '{missingCharacters}' in font '{asset.name}'. Consider adding a fallback font.");
}
}
}
}
}