GetComponent for UI Text

I was working on my game I wanted to change text by script, I thought it was simple enough I would just use GetComponent() 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

using UnityEngine;

public class HealthBarControl : MonoBehaviour
{
    //Game object with Text
    public GameObject HpText;
   
    //Just something I want print with the Text (don't worry about this
    private PlayerStats PlayerStats;

    //This is supposedly how I get the text
    private Text UIText;


    private void Awake()
    {
        PlayerStats = Player.GetComponent<PlayerStats>();
       //This is supposedly calling the component
        UIText = HpText.GetComponent<Text>();
    }

    void Update()
    {
     
        //Prints the Current health of the player also doesn't work
        UIText.text = PlayerStats.PlayerHealth + "/hp";
    }
}

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

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(); If there’s a conflict you can try the fully qualified version GetComponent<UnityEngine.UI.Text>()

4 Likes

Wow! thanks a lot!

Thanks…

33333

Thanks, just a library issue - big PREESH!