Dynamically Change Font size

Announcements, support questions, and discussion for the Dialogue System.
Post Reply
Albyd
Posts: 29
Joined: Thu Jul 21, 2022 4:46 pm

Dynamically Change Font size

Post by Albyd »

Hi there,
I'm wondering if it's possible to change font size dynamically.
I'm working on some accessibility features and I want to make a button that increases the size of the font by X every time I click on it.
Is it possible?

Many thanks
User avatar
Tony Li
Posts: 21033
Joined: Thu Jul 18, 2013 1:27 pm

Re: Dynamically Change Font size

Post by Tony Li »

Hi,

There isn't anything specifically built into the Dialogue System for this, but I assume you'd want to apply the font size change for all text elements anyway, not just the Dialogue System ones.

You could add a script containing code similar to this to your text elements:

Code: Select all

using UnityEngine;
using UnityEngine.UI;

public class FontSizeAdjuster : MonoBehaviour
{
    public static float fontScale = 1.0; // Scale all fonts by this amount.

    private Text text;
    private int originalFontSize;

    void Awake() 
    { 
        text = GetComponent<Text>()
        originalFontSize = text.fontSize;
    }

    void OnEnable()
    {
        UpdateFontSize();
    }

    public void UpdateFontSize()
    {
        text.fontSize = Mathf.RoundToInt(fontScale * originalFontSize);
    }
}
This assume you're using Text elements, but you could use the same approach for TextMeshProUGUI elements.

To change the font size, change the fontScale static variable. Whenever the Text element's GameObject is activated, it will update the font size. You can also manually call UpdateFontSize() after changing the fontScale variable:

Code: Select all

FontSizeAdjuster.fontScale = /*some value*/;
foreach (var fontSizeAdjuster in FindObjectsOfType<FontSizeAdjuster>())
{
    fontSizeAdjuster.UpdateFontSize();
}
Post Reply