NullReferenceException
Hi everyone.
I'm trying to write a simple 12 hour timer in C# to be displayed on the canvas. The time itself is displaying, but does not count up because Unity keeps spitting back this error:
NullReferenceException: Object reference not set to an instance of an object timeOfDay.Update () (at Assets/scripts/timeOfDay.cs:28)
The weird thing is, the object on line 28 is declared
timer.text = time;
and when I build the code inside of MonoDevelop, it returns no errors whatsoever. If i comment out this part, Unity returns the same error but on line 37
amPM.text = "pm";
and 41
amPM.text = "am";
As you can see in my full code below, these 3 things are declared, and they are assigned via the inspector.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
public class timeOfDay : MonoBehaviour {
float myTimer;
public Text timer;
public float modifier;
TimeSpan t;
public bool TOD;
public Text amPM;
void Update ()
{
t = TimeSpan.FromSeconds (Time.time * modifier) + new TimeSpan (4, 0, 0);
if (t.Hours >= 12) {
t -= new TimeSpan (12, 0, 0);
}
string time = string.Format("{0:00}:{1:00}", t.Hours, t.Minutes);
Debug.Log (time);
timer.text = time;
if (t.Hours >=11 && t.Minutes >= 59)
{
TOD =! TOD;
}
if (TOD == false)
{
amPM.text = "pm";
}
else
{
amPM.text = "am";
}
}
}
Thanks in advance for your help, really not sure what I'm doing wrong.
Answer by iwaldrop · Nov 26, 2015 at 04:22 AM
Honestly it seems like the Text components are not assigned. Those are the only things there that could be null.
Text.text is a property, it's simply a string value, and your time field is assigned just above; even if it was null you can assign null to a string, so there won't be any problem there either.
The only thing that is referenced on line 28 is your Text Component, so I'd double check that it is indeed assigned, or that you don't have two of them in your scene accidentally where one is not.
Also, you should maybe put in some checks in OnEnable that all the things that will be needed in Update are present. You can set enabled to false and log an error or warning if they're not.
Thanks for the fast reply!
That fixed the error message, so big thank you for that. Only issue now is the time still does not move, it stays stuck at 4:00pm. Any ideas why that might be?
Is the component enabled? Is multiplier
set to a value greater than 0?
Yeah it's enabled and multiplier
is set to 2.