Search Unity

  1. New Unity Live Help updates. Check them out here!

    Dismiss Notice

Unity UI GetComponent for UI Text

Discussion in 'UGUI & TextMesh Pro' started by Antnest8, Mar 26, 2020.

  1. Antnest8

    Antnest8

    Joined:
    Jan 3, 2020
    Posts:
    3
    I was working on my game I wanted to change text by script, I thought it was simple enough I would just use GetComponent<Text>() or something similar, but Visual Studios didn't recognize Text as a component so I thought maybe it is GUIText? A But Unity said that there was no GUIText component in the game object I was accessing. All other attempts brought similar results of either it not being a component or it not being a component that was present. I should note that I was also attempting accessing the Text (script) from a different game object.

    Here's my code
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class HealthBarControl : MonoBehaviour
    4. {
    5.     //Game object with Text
    6.     public GameObject HpText;
    7.    
    8.     //Just something I want print with the Text (don't worry about this
    9.     private PlayerStats PlayerStats;
    10.  
    11.     //This is supposedly how I get the text
    12.     private Text UIText;
    13.  
    14.  
    15.     private void Awake()
    16.     {
    17.         PlayerStats = Player.GetComponent<PlayerStats>();
    18.        //This is supposedly calling the component
    19.         UIText = HpText.GetComponent<Text>();
    20.     }
    21.  
    22.     void Update()
    23.     {
    24.      
    25.         //Prints the Current health of the player also doesn't work
    26.         UIText.text = PlayerStats.PlayerHealth + "/hp";
    27.     }
    28. }
    29.  
    Yet every time I use "Text" or GUIText it doesn't work. It's also not a TextMesh.
    Note: this is using Unity Engine Version 2018.4.14f1
     
  2. livingtarget

    livingtarget

    Joined:
    Apr 21, 2015
    Posts:
    25
    Visual studio can be a bit funny. So it's usally best to just declare the import yourself:
    using UnityEngine.UI;
    and then it should allow GetComponent<Text>(); If there's a conflict you can try the fully qualified version GetComponent<UnityEngine.UI.Text>()
     
  3. Antnest8

    Antnest8

    Joined:
    Jan 3, 2020
    Posts:
    3
    Wow! thanks a lot!
     
unityunity