Home > Mobile >  Unity changing text with script c#
Unity changing text with script c#

Time:06-14

I'm trying to add a scoring method in my Unity phone game by changing the UI text. Here is My code:

using UnityEngine;
using UnityEngine.UI;

public class ScoreDisplay : MonoBehaviour
{
    // Start is called before the first frame update
    [SerializeField]private Text m_MyText;

    void Start()
    {
        m_MyText.text = "This is my text";
    }

    // Update is called once per frame
    void Update()
    {
         m_MyText.text = "UWU";   
    }
}

Nothing pops up when I search for a text object:

Nothing pops up when I search for a text object

And I cannot drag the mesh text into the public variable. Any help would be appreciated, thank you.

CodePudding user response:

Text is a legacy element and is mostly unused. Instead, you want Text Mesh Pro's text component which is under the TMPro namespace. The componant is called TextMeshProUGUI.

Replace

[SerializeField]private Text m_MyText;

with

[SerializeField]private TMPro.TextMeshProUGUI m_MyText;

The TextMeshProUGUI componant has a text field, so your code should work as normal after replacing the line.

  • Related