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?