But when I play the field is empty.
This happens because GameObject.GetComponent()
searches for the component on the GameObject
you are calling it from and as you can clearly see on your screenshot the UIManager doesn't include a Text
object.
You seem to have assigned the Text
component directly that is correct, but what you have to think about is that you are resetting the variable in Awake
because you replace it with null
.
What happens in your code:
[SerializeField]
private Text _scoreText; // Assigned in inspector.
private void Awake() {
// Sets scoreText to null, because the UIManager has no Component Text.
_scoreText = GetComponent<Text>();
}
Instead you should just remove the code in the Awake
method all together and rather add a check to ensure it's set in the inspector.
Replaced Awake Method:
private void Awake() {
// Check if scoreText was assigned in the inspector.
if (_scoreText == null) {
Debug.LogWarning("ScoreText has not been assigned in the inspector.");
// Get the gameObject with the given name.
GameObject textGo = GameObject.Find("Text GameObject Name");
// Attempt to get the component from the given GameObject.
if (textGo.TryGetComponent(out Text text)) {
_scoreText = text;
}
}
}
If it isn't set you could always use GameObject.Find()
combined with
GameObject.TryGetComponent()
to attempt to get the Text
Component from the GameObject
with the given name.