UI element bug?
Hi, I assign the text element in the inspector as shown.
However, when I run the game, the inspector looks like this.
I get a "NullReferenceExecption: Object Reference not set to an instance of an object". Below is the code I am using.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ScoreKeeper : MonoBehaviour {
public Text scoreText;
public static int score;
// Use this for initialization
void Start () {
scoreText = gameObject.GetComponent<Text> ();
score = 0;
}
// Update is called once per frame
void Update () {
scoreText.text = "Score: " + score.ToString();
}
}
Answer by TBruce · Dec 22, 2016 at 07:07 PM
This is no bug. The reason you are getting an error is that you are first assigning the UI.Text element in the inspector but then you nullifying it in the Start()
function with this
scoreText = gameObject.GetComponent<Text> ();
you can either remove the statement above or do this instead
if (scoreText == null)
{
scoreText = gameObject.GetComponent<Text> ();
}
Note: The assignment requires that a UI.Text
component be attached to the current game object (the same game object that ScoreKeeper
is attached to).
Your answer
Follow this Question
Related Questions
How to make mesh render objects overlay UI? 1 Answer
Drop object to exact place 1 Answer
RectTransform Left Right Bottom Top 0 Answers
C# - The name does not exist in the current context 1 Answer
Multiple Character selection UI 0 Answers