0

I want to use script to dynamically change the font of a specific button label in Unity. However, my efforts haven't worked.

I have created a simple game. The game's interface has multiple buttons on the canvas, with unique text labels on each button. The buttons are canvas elements (UI button) with a sub element (text - TextMeshPro) which provides the text label for each of the buttons.

In the code example below, all of the code works except the last full line beginning, "buttonLabelText.font =". I can, for example, use the rest of the code to easily change what the button says (change the button text). However, I cannot change the font (or do other font manipulations like change the size of the font).

Additional info: The below code does not throw any errors. I am using TextMeshPro. The desired font is in the following folder: Assets > TextMesh Pro > Resources > Fonts & Materials. The font is saved in SDF format.

Additional context: I want to change the font via script because there are multiple buttons on the game UI, all of which will change fonts at certain times. So, the script would allow me to more easily specify which buttons should change fonts at certain times.

Any potential solutions?

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    using TMPro;

    public class FontManipulation : MonoBehaviour {
    public TMP_FontAsset ChillerSDF; // ChillerSDF is the font I want for the button label text.
    private TextMeshProUGUI buttonLabelText; // buttonLabelText is the actual text within the button label

    void Start() {

        TextMeshProUGUI buttonLabelText = GameObject.Find("ButtonLabel").GetComponent<TextMeshProUGUI>(); // This code finds the correct button label among multiple button labels in the scene, and grabs the TextMesh Pro GUI. This code works (I can use it to change what the text says, for example).
        buttonLabelText.font = ChillerSDF; // This code should change the font to the desired font, but does not work.
    }
    }
stevemn
  • 1
  • 1
  • 2

1 Answers1

1

I had the same problem as you and I solved it by getting TMP_Text instead of TextMeshProUGUI

public TMP_FontAsset ChillerSDF; 
private TMP_Text buttonLabelText; //TMP_Text instead of TextMeshProUGUI
    
void Start() { 
    TMP_Text buttonLabelText = GameObject.Find("ButtonLabel").GetComponent<TMP_Text>();
    buttonLabelText.font = ChillerSDF; // This code should work now
}
nine
  • 11
  • 1