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()
{
}
}