Home > Enterprise >  What is wrong with my stopwatch in Unity?
What is wrong with my stopwatch in Unity?

Time:07-11

I created a script to display how long the player has played my game.

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

public class Stopwatch : MonoBehaviour
{
    bool stopwatchActive = false;
    float currentTime;
    public Text currentTimeText;
    
    // Start is called before the first frame update
    void Start()
    {
        currentTime = 0;
        StartStopwatch();
    }

    // Update is called once per frame
    void Update()
    {
        if (stopwatchActive == true)
        {
            currentTime = currentTime   Time.deltaTime;
        }
        TimeSpan time = TimeSpan.FromSeconds(currentTime);
        currentTimeText.text = time.Seconds.ToString();
    }

    public void StartStopwatch()
    {
        stopwatchActive = true;
    }

    public void StopStopwatch()
    {
        stopwatchActive = false;
    }
}

I assigned everything and tested it. Everything works perfectly fine, but I get this error in Unity:

NullReferenceException: Object reference not set to an instance of an object
Stopwatch.Update () (at Assets/Scripts/Other/Stopwatch.cs:28)

(I get no error in VS)

Is there something wrong with the code?

(Sorry if it is a dumb mistake, because I am new to scripting)

CodePudding user response:

It seems that your currentTimeText public variable is not assigned in the inspector.

CodePudding user response:

The exception you are receiving is a Null Reference Exception. Meaning that you are trying to change or read data from Null. A variable that was not set.

Better explained here: What is a NullReferenceException, and how do I fix it?

The exception occurred at line 27, in the Update Method.

Edit:

Tip, insert Console.Log(variable); at the start of the Update method.

  • Related