Unity 3D实现点击按钮显示游戏当前计时功能求助
Hey there! Let's get that button functionality sorted so clicking "CurrentTime" shows the current game timer on your UI Text. Here's a straightforward step-by-step solution:
Step 1: Refactor the Script for Reusable Logic
First, we'll wrap the time display logic into a reusable method, then create a public method your button can trigger. This keeps the code clean and avoids redundant work.
Here's the updated Timer script:
using UnityEngine; using UnityEngine.UI; public class Timer : MonoBehaviour { public int Hours = 0; public int Minutes = 0; public Text m_text; // For real-time timer display private float timestart; public Text ending; // Text to update when button is clicked void Awake() { timestart = GetInitialTime(); } void Start () { // Initialize the real-time timer display UpdateTimeDisplay(m_text); } private void Update() { if (timestart > 0f) { // Update timer value (adjust 0.25f if you need different time flow speed) timestart += Time.deltaTime * 0.25f; // Refresh the real-time display UpdateTimeDisplay(m_text); } // Removed automatic updates to 'ending' text – we'll only update it on button click } // Reusable method to update any Text component with current time private void UpdateTimeDisplay(Text targetText) { if (timestart > 0f) { int currentHours = GetLeftHours(); int currentMinutes = GetLeftMinutes(); targetText.text = $"{currentHours}:{currentMinutes.ToString("00")}"; } else { targetText.text = "00:00"; } } // Public method for the button to call public void OnCurrentTimeButtonClicked() { UpdateTimeDisplay(ending); } private float GetInitialTime() { return Hours * 60f + Minutes; } private int GetLeftHours() { return Mathf.FloorToInt(timestart / 60f); } private int GetLeftMinutes() { return Mathf.FloorToInt(timestart % 60f); } }
Step 2: Bind the Method to Your Button in Unity Editor
- Select your "CurrentTime" Button GameObject in the Hierarchy.
- In the Inspector panel, scroll down to the On Click () section.
- Click the
+button to add a new event. - Drag the GameObject with your
Timerscript attached into the empty "None (Object)" slot. - Click the dropdown menu, navigate to Timer > OnCurrentTimeButtonClicked().
That's all! Now when you click the "CurrentTime" button, the ending Text component will show the current game timer value (like "24:04" after 4 minutes of gameplay, matching your time speed setting).
Quick Note on Time Speed
The line timestart += Time.deltaTime * 0.25f makes the game timer run at 25% of real-time speed. If you want game time to match real-time exactly, replace that line with:
timestart += Time.deltaTime / 60f;
This converts real-time seconds into minutes, so 60 seconds of real time adds 1 minute to the game timer.
内容的提问来源于stack exchange,提问作者Awais Ahmed

