I got this code of a timer, it is composed of a fill and a text because I don't want to only see numbers decreasing, so it was decided to use a fill to make it more striking. It works correctly but I want the counter to restart when it reaches 0. I want it to be an infinite counter, that when the scenario is running, when it reaches 0 it restarts without having to pause and play it again. Have problems when trying to restart the fill
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();
}
}
To set the time, a small code is used, calling the functions of the previous code.
public class Demo : MonoBehaviour
{
[SerializeField] Timercountdown timer1;
// Start is called before the first frame update
private void Start()
{
timer1.SetDuration(30).Begin();
}
}