Accessing UI Text in Code

Hey Guys,
i am new to Unity and watch only a few tutorials.
Currently i am trying to make a UI for my game.
But i got a minor Problem, i am not sure how i should access the text-element of the UI in Code.

I could give my PlayerController class the Canvas object and search for the Text-Element i want to change or i could give the Controller the text-Object directly.

I can see advantages/disadvantages with both.

But what would be the better solution?
Or is there any other solution?

Here is a example Code with i wrote.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class PlayerController : MonoBehaviour
{

    public GameObject playerCanvas;
    public GameObject moneyText;

    public int moneyCount;
    public int health;

    // Use this for initialization
    void Start()
    {
        health = 100;
        moneyText.GetComponent<Text>().text = "Current money: " + moneyCount;
        List<Text> texts = new List<Text>();
        playerCanvas.GetComponentsInChildren<Text>(texts);

        foreach (Text text in texts)
        {
            if (text.name == "HealthText")
            {
                text.text = "Current Health: " + health;
            }
        }
    }

    // Update is called once per frame
    void Update()
    {

    }
 }

There are a few different ways to pass the value to the UI.

But you shouldn’t rely on your second choice of searching for the right field. Mainly because it’s a string search and if you change the name of the text field you would have to change it in the code as well.

I would just do like you did with money and link the field in the inspector and update the value whenever you need to.

There’s also thoughts about what script is updating the field and where that field is located, but those are less important as it has a bit to do with personal preference and experience.

Definitely do not compare gameobject names, since it would prevent you from renaming it in the scene (without refactoring the code).

I would prefer to give a reference to the actual component (Text, not GameObject), so there’s no need to look for the component in code.

public class PlayerController : MonoBehaviour
{
    public Text moneyText;
}
1 Like

Thank you!