Search Unity

How to change text programatically?

Discussion in 'UGUI & TextMesh Pro' started by hangarter, Feb 11, 2020.

  1. hangarter

    hangarter

    Joined:
    Mar 14, 2016
    Posts:
    23
    Hi All,

    I tried to find on the forum but I couldn't, how can I from the scripting API get the TextMesh UI Text component and update it's text?
    On Visual Studio it didn't work importing TMPro namespace

    All Best
     
  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    TextMesh is built into Unity, and you can access the API through a TextMesh object without using a namespace. TextMeshPro is a package you have to import using the "Package Manager" under the "Window" dropdown at the top of Unity.

    You can only import the TMPro namespace in your code if you've imported the TextMeshPro package into your Unity project. With TextMeshPro, you get both 3D object (TextMeshPro) and UI objects (TextMeshProUGUI), but without TextMesh pro, all you get is 3D objects and no UI.

    The "Text" object you can add to your UI is separate from TextMesh, and you can access it as a "Text" object once you import the UnityEngine.UI namespace.

    Hope that clears it up, good luck!
     
  3. Stephan_B

    Stephan_B

    Joined:
    Feb 26, 2017
    Posts:
    6,595
    The TextMesh Pro package is included with Unity by default. Updates to TMP are first made available via the Package Manager and eventually replace the default package included with Unity.

    To use TMP, you have to first import the TMP Essential Resources and strongly recommended to import the TMP Examples & Extras which includes examples such as how to change the text via code. See Example 21 - Script Examples and 22 - Basic Scripting Example.

    To import the TMP Essential Resources and TMP Examples & Extras, go to the "Window - TextMeshPro - Import ..." menu.

    The namespace should be available to add to your script by simply adding "using TMPro;" but if you are using .asmdef for your own scripts, you need to add a reference to the Unity.TextMeshPro assembly to your .asmdef.
     
  4. hangarter

    hangarter

    Joined:
    Mar 14, 2016
    Posts:
    23
    Thank you all! I had a "TextMeshPro - Text (UI)" component already on the scene.
    So I imported it to a private field using [SerializeField] and added using TMPro; on the headers :)