The question is answered, right answer was accepted
Null reference exception to a non-null text object?
Hi everyone--
I'm making my first non-tutorial game in Unity and I seem to be having an issue with setting text. I'm trying to make a score text object. Here's my code: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class EnemyDies : MonoBehaviour {
public Rigidbody2D rb;
public static int score;
public Text text;
// Use this for initialization
void Awake () {
text = GetComponent<Text> ();
}
// Update is called once per frame
void Update () {
string scores = score.ToString();
text.text = scores;
}
public void OnTriggerEnter2D (Collider2D attack)
{
if (attack.gameObject.CompareTag ("Attack")) {
if (transform.position.y <= 0.25F && transform.position.y >= -0.25F) {
score = score + 2;
} else {
score = score + 1;
}
transform.position = new Vector3 (0, 6, 0);
rb.velocity = new Vector2 (0, 0);
}
if (attack.gameObject.CompareTag ("Boundary")) {
transform.position = new Vector3 (0, 6, 0);
rb.velocity = new Vector2 (0, 0);
}
}
}
Both text and rb are defined in the editor. I keep getting a null reference exception on the line text.text = scores, even though this is how all the tutorials I could find did this. Can anyone help?
@AlphafishGames in this case scores
must be null. If the objects have been set in the inspector that's the only possible explanation.
What value does scores
have when it gets assigned to text.text
?
Answer by AlphafishGames · May 12, 2017 at 03:04 AM
Okay, never mind. It turns out I was being stupid and I only needed to put text.text = score.ToString();. It must've been the GetComponent in the awake function that was messing me up or something. It's resolved now. :)