Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Cannot implicitly convert type 'string' to 'TMPro.TextMeshProUGUI'

Discussion in 'Scripting' started by Ciava, Jun 11, 2022.

  1. Ciava

    Ciava

    Joined:
    Jun 1, 2018
    Posts:
    50
    Hello!
    I know this is a super-simple and noob question but I am having some problems with a simple task:

    Code (CSharp):
    1. public TextMeshProUGUI test_;
    2.  
    3.     private void Start()
    4.     {
    5.         int number = 10;
    6.         test_ = "How stressed am I? " + number;
    7.         test_ = "How stressed am I? " + number.ToString();
    8.  
    9.     }
    I "Cannot implicitly convert type 'string' to 'TMPro.TextMeshProUGUI'"

    How does it works please?

    Thank you and sorry for my noobness
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    6,015
    Well, TextMeshProUGUI is a component. It's not a string. You need to set its text with either the .text property, or the .SetText() method.
     
    fhbaroni, ditlevrisdahl and Ciava like this.
  3. Ciava

    Ciava

    Joined:
    Jun 1, 2018
    Posts:
    50
    :(:(:(
    I swear I feel dumb. I ALWAYS used this and this morning i missed that ".text =".

    Thank you so much! :oops:
     
    Wiikki likes this.
  4. FinnM

    FinnM

    Joined:
    Aug 16, 2017
    Posts:
    1
    for anyone looking for an answer you need to add .text as you are changing the text value of the component not the component itself.

    Ex
    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using UnityEngine.UI;
    4. using TMPro;
    5.  
    6. public class HealthBar : MonoBehaviour
    7. {
    8.     public Slider slider;
    9.     public TMP_Text text_HealthValue;
    10.  
    11.     public void SetMaxHealth(float maxHealth)
    12.     {
    13.         slider.maxValue = maxHealth;
    14.         slider.value = maxHealth;
    15.         text_HealthValue.text = maxHealth.ToString();
    16.     }
    17.  
    18.     public void SetHealth(float health)
    19.     {
    20.         slider.value = health;
    21.         text_HealthValue.text = health.ToString();
    22.     }
    23. }
    24.  
    25.  
    26.  
     
    Last edited: Jul 24, 2023