97 lines
2.9 KiB
C#
97 lines
2.9 KiB
C#
using UnityEngine;
|
|
using TMPro;
|
|
|
|
public class runningTime : MonoBehaviour
|
|
{
|
|
public TextMeshProUGUI allRunningTime;
|
|
public AudioSource bgMusicAudioSource; // optional: can be assigned in inspector
|
|
|
|
// progressLine/zhuangshi (1): Scale.x is driven by playedTime/totalLength (0..1)
|
|
private Transform progressLineDecor;
|
|
private Vector3 progressLineDecorBaseScale;
|
|
private bool progressLineDecorBaseScaleCached;
|
|
|
|
private GameManager gm;
|
|
|
|
void Start()
|
|
{
|
|
gm = Object.FindAnyObjectByType<GameManager>();
|
|
if (bgMusicAudioSource == null && gm != null)
|
|
{
|
|
bgMusicAudioSource = gm.musicSource;
|
|
}
|
|
|
|
// Cache progress bar transform (optional)
|
|
try
|
|
{
|
|
var go = GameObject.Find("progressLine/zhuangshi (1)");
|
|
if (go != null) progressLineDecor = go.transform;
|
|
if (progressLineDecor != null)
|
|
{
|
|
progressLineDecorBaseScale = progressLineDecor.localScale;
|
|
progressLineDecorBaseScaleCached = true;
|
|
}
|
|
}
|
|
catch { }
|
|
|
|
// ensure UI shows zero initially
|
|
if (allRunningTime != null) allRunningTime.text = "00:00";
|
|
UpdateProgressBar(0f);
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
// Display played time after the game manager indicates playback actually started.
|
|
// Do not require isPlaying so pause will keep the last value instead of resetting.
|
|
if (gm != null && gm.PlaybackStarted && bgMusicAudioSource != null && bgMusicAudioSource.clip != null)
|
|
{
|
|
float played = Mathf.Max(0f, bgMusicAudioSource.time);
|
|
float total = Mathf.Max(0.0001f, bgMusicAudioSource.clip.length);
|
|
|
|
if (allRunningTime != null)
|
|
allRunningTime.text = FormatMMSS(played);
|
|
|
|
UpdateProgressBar(played / total);
|
|
return;
|
|
}
|
|
|
|
{
|
|
if (allRunningTime != null) allRunningTime.text = "00:00";
|
|
UpdateProgressBar(0f);
|
|
}
|
|
}
|
|
|
|
private void UpdateProgressBar(float ratio01)
|
|
{
|
|
if (progressLineDecor == null)
|
|
{
|
|
try
|
|
{
|
|
var go = GameObject.Find("progressLine/zhuangshi (1)");
|
|
if (go != null) progressLineDecor = go.transform;
|
|
}
|
|
catch { }
|
|
}
|
|
if (progressLineDecor == null) return;
|
|
if (!progressLineDecorBaseScaleCached)
|
|
{
|
|
progressLineDecorBaseScale = progressLineDecor.localScale;
|
|
progressLineDecorBaseScaleCached = true;
|
|
}
|
|
|
|
float r = Mathf.Clamp01(ratio01);
|
|
var s = progressLineDecorBaseScale;
|
|
s.x = r;
|
|
progressLineDecor.localScale = s;
|
|
}
|
|
|
|
private static string FormatMMSS(float seconds)
|
|
{
|
|
if (seconds < 0f) seconds = 0f;
|
|
int total = Mathf.FloorToInt(seconds);
|
|
int mins = total / 60;
|
|
int secs = total % 60;
|
|
return mins.ToString("00") + ":" + secs.ToString("00");
|
|
}
|
|
}
|