提问人:DanielVP19 提问时间:7/7/2023 最后编辑:DanielVP19 更新时间:7/7/2023 访问量:23
如何使用填充和文本重置计时器
How to reset a timer with his fill and text
问:
我得到了这个计时器的代码,它由填充和文本组成,因为我不想只看到数字递减,所以决定使用填充来使其更加醒目。它工作正常,但我希望计数器在达到 0 时重新启动。 我希望它是一个无限计数器,当场景运行时,当它达到 0 时,它会重新启动,而无需暂停并再次播放。尝试重新启动填充时出现问题
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Timercountdown : MonoBehaviour
{
[SerializeField] private Image uifill;
[SerializeField] private Text uitext;
public int Duration { get; private set; }
private int remainingDuration;
private void Awake()
{
ResetTimer() ;
}
private void ResetTimer()
{
uitext.text = "00:00";
uifill.fillAmount = 0f;
Duration = remainingDuration = 0;
}
public Timercountdown SetDuration(int seconds)
{
Duration = remainingDuration = seconds;
return this;
}
public void Begin()
{
StopAllCoroutines();
StartCoroutine(UpdateTimer());
}
private IEnumerator UpdateTimer()
{
while(remainingDuration > 0)
{
UpdateUI(remainingDuration);
remainingDuration--;
yield return new WaitForSeconds(1f);
}
End();
}
private void UpdateUI(int seconds)
{
uitext.text = string.Format("{00:00}:{01:00}", seconds/60 , seconds%60);
uifill.fillAmount = Mathf.InverseLerp(0, Duration, seconds);
}
public void End()
{
ResetTimer();
}
private void OnDestroy()
{
StopAllCoroutines();
}
}
为了设置时间,使用一个小代码,调用前面代码的函数。
public class Demo : MonoBehaviour
{
[SerializeField] Timercountdown timer1;
// Start is called before the first frame update
private void Start()
{
timer1.SetDuration(30).Begin();
}
}
答: 暂无答案
评论