You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Unity中使用C#开发计时功能:类代码相关技术问询

Unity C# Timer Class Improvements & Fixes

Let's take a look at your timer code and work through some fixes, optimizations, and feature additions to make it more reliable and flexible for your project.

First, let's address the immediate issues in your partial code:

Quick Fixes

  • Typo Correction: You have finnished instead of finished — this will cause compilation errors or unexpected behavior, so fix that spelling first.
  • Unfinished Seconds Calculation: Your cut-off string se... line should calculate the remaining seconds. A basic version would be string seconds = ((int)t % 60).ToString();, but we can do better than that.

Key Improvements & Feature Additions

Here are actionable enhancements to make your timer more robust:

1. Proper Time Formatting (Zero-Padding)

Right now, your timer will display single-digit values (e.g., "5" minutes instead of "05") which looks unpolished. Use ToString("D2") to automatically pad numbers to two digits:

int minutes = Mathf.FloorToInt(t / 60);
int seconds = Mathf.FloorToInt(t % 60);
timerText.text = $"{minutes:D2}:{seconds:D2}";

2. Add Pause/Resume/Reset Functionality

Your current code only starts and stops the timer. Adding pause/resume/reset makes it reusable for scenarios like game pauses or restarting levels:

  • Track paused time to resume from where you left off
  • Use a state enum to manage running/paused/stopped states (avoids messy boolean checks)

3. Reduce Performance Overhead

Update() runs every frame, and frequent string operations can add up. Instead of updating the UI every frame:

  • Use InvokeRepeating() to update the UI every 0.1 seconds (or 1 second if you don't need millisecond precision)
  • Or cache formatted values to avoid redundant calculations

4. Decouple Timer Logic from UI

Instead of directly referencing a Text component, you can expose the elapsed time as a property and let UI scripts listen for updates, or use events to notify other systems when the timer changes.

Full Improved Timer Code

Here's a complete, refactored version incorporating all these suggestions:

using UnityEngine;
using UnityEngine.UI;

public class HelpMeTimer : MonoBehaviour
{
    public Text timerText;
    private float startTime;
    private float pausedElapsedTime;
    private TimerState currentState = TimerState.Stopped;

    // Enum to clearly track timer state
    private enum TimerState
    {
        Running,
        Paused,
        Stopped
    }

    void Start()
    {
        // Initialize UI to 00:00 on start
        ResetTimer();
        StartTimer();
    }

    void Update()
    {
        if (currentState != TimerState.Running) return;

        float elapsedTime = Time.time - startTime;
        UpdateTimerDisplay(elapsedTime);
    }

    private void UpdateTimerDisplay(float elapsedTime)
    {
        int minutes = Mathf.FloorToInt(elapsedTime / 60);
        int seconds = Mathf.FloorToInt(elapsedTime % 60);
        int milliseconds = Mathf.FloorToInt((elapsedTime * 100) % 100);

        // Format with zero-padding for clean display
        timerText.text = $"{minutes:D2}:{seconds:D2}:{milliseconds:D2}";
    }

    // Public methods to control the timer from other scripts
    public void StartTimer()
    {
        startTime = Time.time - pausedElapsedTime;
        currentState = TimerState.Running;
    }

    public void PauseTimer()
    {
        if (currentState != TimerState.Running) return;

        pausedElapsedTime = Time.time - startTime;
        currentState = TimerState.Paused;
    }

    public void ResumeTimer()
    {
        if (currentState != TimerState.Paused) return;

        StartTimer();
    }

    public void ResetTimer()
    {
        currentState = TimerState.Stopped;
        pausedElapsedTime = 0f;
        timerText.text = "00:00:00";
    }

    public void FinishTimer()
    {
        currentState = TimerState.Stopped;
        // Optional: Trigger an event when the timer finishes
        // OnTimerFinished?.Invoke();
    }

    // Optional: Add an event for other scripts to listen to timer completion
    // public event System.Action OnTimerFinished;
}

Extra Tips

  • Assign the UI Component: Make sure you drag your Text element into the timerText field in the Inspector to avoid null reference errors.
  • Adjust Precision: If you don't need milliseconds, remove that part from the display and update logic.
  • Global Timer: If you need a single global timer, you can turn this into a singleton (add a static instance property) to easily access it from any other script.

内容的提问来源于stack exchange,提问作者ravi tanwar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:59:23