Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

I need help with my script

Discussion in 'Getting Started' started by stopmotionshortschannel, Apr 23, 2024.

  1. stopmotionshortschannel

    stopmotionshortschannel

    Joined:
    Apr 23, 2024
    Posts:
    1
    I'm trying to make a countdown timer for my game that, when it finishes, it changes the scene, but i keep getting this error:

    here is the error:

    NullReferenceException: Object reference not set to an instance of an object
    NewBehaviourScript1.Update () (at Assets/scripts/Timer.cs:20)


    here is my script:


    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;

    public class NewBehaviourScript1 : MonoBehaviour
    {
    float currentTime;
    public int startMinutes;
    public Text currentTimeText;
    // Start is called before the first frame update
    void Start()
    {
    currentTime = startMinutes * 60;
    }

    // Update is called once per frame
    void Update()
    {
    currentTimeText.text = currentTime.ToString();
    }
    }
     
  2. dstears

    dstears

    Joined:
    Sep 6, 2021
    Posts:
    217
    Hi, when you post code to the forums, please use the code tags. There is information about that here:
    https://forum.unity.com/threads/using-code-tags-properly.143875/

    Null reference exceptions are very common, so it would be a good idea to take a look at this thread:
    https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

    Remember that the error message will tell you which line the error occurs on. In your case, it reports line 20. The only reference on this line is to currentTimeText, so you likely did not set this reference in the inspector.