Timer causes trouble

Resolved

Post these errors.
Also: use code tags for code.

Usually they end with “(xx,yy)” where xx is the line number, and yy the character number within that line.

Also do this, learn how to use the debugger, it will save you a TON of headaches and it’s very instructive to see your own code executing line by line (and as a side effect, it’ll encourage you to write more lines rather than fewer but very looooong lines ;)):

Then ChatGPT didn’t help you with the code. ChatGPT will output things with an air of confidence even if those things will not even remotely function and should not be used until this is resolved or you are experienced enough a developer to recognize these issues. What does “the game cannot start” mean? Are there errors? What’s happening?

Also, use code tags.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class Timer : MonoBehaviour
{
    [SerializeField] TextMeshProUGUI timerText;
    [SerializeField] float initialTime;
    float remainingTime;

    bool timerStarted = false;

// Update is called once per frame
    void Update()
    {
        if (timerStarted)
        {
            remainingTime -= Time.deltaTime;
            if (remainingTime <= 0)
            {
                remainingTime = 0;
                timerText.color = Color.red;
            }
        }

        int minutes = Mathf.FloorToInt(Mathf.Abs(remainingTime) / 60);
        int seconds = Mathf.FloorToInt(Mathf.Abs(remainingTime) % 60);
        timerText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
    }

    public void StartTimer()
    {
        remainingTime = initialTime;
        timerStarted = true;
    }
}

Where are you calling StartTimer()? The code that ChatGPT generated literally can not function if you aren’t calling that because your default timer state is false.

2 Likes

ChatGPT is an extremely bad idea for a beginner to use. If you fail to notice or understand that you’ve mistyped time.deltaTime when you meant to type Time.deltaTime then you shouldn’t be using an AI to generate your code for you.

2 Likes

You’re immediately setting your timer to 0 because of your if statement on line 18. You’re checking if the remaining time is more than 0 (which it will be) and then setting the remaining time to zero. Because of this, the Mathf.Abs function is returning the absolute value of your now negative counting timer.

4 Likes