Avarage cat enjoyer
Avarage cat enjoyer

Reputation: 133

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.

Upvotes: 2

Views: 19778

Answers (3)

JottoWorol
JottoWorol

Reputation: 321

To modify TextMeshPro components, you have to use TMP_Text class.

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

    void Update()
    {
         coins.text = "text"; //or coins.SetText(“text”);
    }
}

Upvotes: 4

alexpro_23
alexpro_23

Reputation: 84

You need to reference the tmp text component instead of the normal Unity text one: Instead of GetComponent<Text>(); do GetComponent<TextMeshProUGUI>();

Of course don’t forget:

using TMPro;

on top of your code.

Upvotes: 1

Maciejowski
Maciejowski

Reputation: 116

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";
    }
}

Upvotes: 10

Related Questions