Problems accessing child text from canvas
I'm working on a with a canvas with two child text objects. First problem is is that I can't figure out how to access one of the specific children from the canvas (HUD) to set the text for just one.
In the interest in making progress and trying to set the score properly (at least, according to the professors specs), I removed one of the text objects and have been trying to set the text via a the HUD. After playing around with a few print statements, but since my text object is getting a null reference, it obviously doesn't properly change the score. I've already confirmed that the object calling HUD works fine, gets and sets score as intended.
(And yes, I'm sure GetComponentInChildren is the wrong way to go about this or something, but that was just the last thing I tried).
Error message:
NullReferenceException: Object reference not set to an instance of an object
HUD.Start () (at Assets/scripts/gameplay/HUD.cs:19)
HUD code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Headsup display
/// </summary>
public class HUD : MonoBehaviour {
[SerializeField]
static Text scoreText;
static int score = 2;
void Start() {
scoreText = GetComponentInChildren<Text>();
scoreText.text = ("Score: " + score); <------ Line 19
}
public static void AddScore(int points)
{
score += points;
scoreText.text = ("Score: " + score);
}
}
,I'm working on a with a canvas with two child text objects. First problem is is that I can't figure out how to access one of the specific children from the canvas (HUD) to set the text for just one.
In the interest in making progress and trying to set it properly (at least, according to the professors specs), I removed one of the text objects and have been trying to set the text (score) via a the HUD. After playing around with a few print statements, but since my text object is getting a null reference, it obviously doesn't properly change the score. I've already confirmed that the object calling HUD works fine, gets and sets score as intended.
Error message:
NullReferenceException: Object reference not set to an instance of an object
HUD.Start () (at Assets/scripts/gameplay/HUD.cs:19)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Headsup display
/// </summary>
public class HUD : MonoBehaviour {
[SerializeField]
static Text scoreText;
static int score = 2;
void Start() {
scoreText = GetComponentInChildren<Text>();
scoreText.text = ("Score: " + score); <------ Line 19
}
public static void AddScore(int points)
{
score += points;
scoreText.text = ("Score: " + score);
}
}
Your answer
Follow this Question
Related Questions
How do I keep child gameobject of UI text 1 Answer
World space canvas child of gameObject 1 Answer
How to fix my GUI Text? 0 Answers
Display rigidbody speed to a world space canvas text 2 Answers