Timer

 avatar
unknown
plain_text
2 days ago
1.4 kB
23
Indexable
using UnityEngine;
using TMPro;

public class Timer : MonoBehaviour
{
    
    public TextMeshProUGUI timerText; 

    public float time = 0f;
    public bool isRunning = true;

    void Start()
    {
        
        if (timerText == null)
        {
            Debug.LogError("FATAL SETUP ERROR: Timer Text (TextMeshProUGUI) is NOT assigned in the Inspector on the Player object! Timer cannot display.");
            isRunning = false;
        }
        else
        {
            DisplayTime(0f);
        }
    }

    void Update()
    {
        
        if (isRunning && timerText != null)
        {
            time = Time.timeSinceLevelLoad;
            DisplayTime(time);
        }
    }

    
    void DisplayTime(float timeToDisplay)
    {
        if (timeToDisplay < 0) timeToDisplay = 0;

        float minutes = Mathf.FloorToInt(timeToDisplay / 60);
        float seconds = Mathf.FloorToInt(timeToDisplay % 60);
        float milliseconds = Mathf.Round((timeToDisplay % 1) * 1000);

        timerText.text = string.Format("{0:00}:{1:00}.{2:000}", minutes, seconds, milliseconds);
    }

    public void StopTimer()
    {
        if (isRunning)
        {
            isRunning = false;
            
            Debug.Log("Timer successfully stopped by Player collision. Final time: " + time.ToString("F3"));

            
        }
    }
}
Editor is loading...
Leave a Comment