- Home /
Why do I get a null reference with this timer?
Hello all,
I can't put my eyes on why do I get a null reference for this C# code for a timer:
public Text timerText;
private float startTime = 300f;
private void Start()
{
timerText = GetComponent<Text>();
}
private void Update()
{
startTime -= Time.deltaTime;
string minutes = (startTime / 60).ToString();
string seconds = (startTime % 60).ToString("f0");
timerText.text = string.Format("{0:0} : {0:00}", minutes, seconds); //this is the null reference line
}
and here's how it looks in the editor. Also for some reason I get double numbers in the text window
Any suggestions??
is the script on the same object that has the Text component?
It is, the script is on the text component of the canvas
Select the error message in the console. It should highlight the gameobject that threw the error. It's proably one you didn't expect.
Answer by Dave-Carlile · Jun 20, 2017 at 01:28 PM
Your timerText
variable isn't being set by the GetComponent
call in Start
.
Since timerText
is a public field it should show up in the inspector. Is there a reason you're not just dragging the Text reference to that field and setting it at edit time? That is the generally recommended approach for hooking up references.
But it solved my problem... is that a coincidence?
I converted your answer to a comment for you. :)
Answer by hexagonius · Jun 20, 2017 at 07:15 PM
It's not at all recommended. If the script is on the same gameobject adding the RequireComponent attribute is recommended.
Hi @hexagonius I've added the RequireComponent and it's working well. Thanks!
any idea why I get double numbers in the text window?? (see picture above)
you had two '0' keys in your format string template. change to:
timerText.text = string.Format("{0: 0} : {1: 00}", $$anonymous$$utes, seconds); //this is the null reference line
Your answer
![](https://koobas.hobune.stream/wayback/20220612124536im_/https://answers.unity.com/themes/thub/images/avi.jpg)