Timer UI not staying on scipt

So, I have a timer script that works but the UI for the countdown won’t stay on the script when I click play. I’m also getting an error when I play that comes up every update so I can almost guarantee it is because of this problem. Quite new to code so might be something small and simple but just haven’t been able to crack it

NullReferenceException: Object reference not set to an instance of an object
Timer.Update () (at Assets/Scripts/Timer.cs:26)3566478--287483--Capture.PNG

I see that in the Start() you are trying to set the Text element to timerSeconds, You need to confirm that this getting done.

something simple like this

void Start()
    {
        timerSeconds = GetComponent<Text> ();
        if(!timerSeconds)
        {
            Debug.Log("timerSeconds was not set, and is null");
        }
    }

if it is not finding the Text then you’ll need to make sure that this script is attached to the Text gameObject, or change the script to look for the Text object. Or remove the Start() and just drag and drop the Text element in Unity.

1 Like

Since TImerSeconds is public, you most likely did a drag and drop based on your screenshot, however, because you did a GetComponent call in Start, you are now telling it to look at the same GameObject as the Timer script and find a Text component and assign it to the TimerSeconds variable. However, if it doesn’t find anything, it just sets the value to null, thus overwriting your drag and drop.

Just remove the part in Start if you are going to drag and drop the target into the variable.

If the text object is in the inspector before you press play then you don’t need to get the component in the Start() method.
However the issue does appear to be that the text object you want is not on the same object as this script resulting in a null ref.

Thanks everyone for the help I just removed the line in the start function.