Search code examples
c#unity-game-enginetext

How to modify UI text via script?


A simple question: I'm trying to modify UI text (TextMeshPro if that makes any difference) via C# script. I am using the following code:

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

public class Coins : MonoBehaviour
{
    public Text coins;
    void Start()
    {
        coins = GetComponent<Text>();
    }

    void Update()
    {
        coins.text = "text";
    }
}

I've done a similar thing in Unity 2018 (I'm currently using Unity 2020.2) and it worked there. For some reason it doesn't work here though. I would appreciate any help.


Solution

  • Changing text in TMP is practicly the same, but you need to add "using TMPro;" and also change variable type. The code should look like this:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    using TMPro;
    
    public class Coins : MonoBehaviour
    {
        public TMP_Text coins;
        void Start()
        {
            coins = GetComponent<TextMeshProUGUI>();
        }
    
        void Update()
        {
            coins.text = "text";
        }
    }