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.
CodePudding user response:
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";
}
}
CodePudding user response:
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.
CodePudding user response:
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”);
}
}