Skip to content

Instantly share code, notes, and snippets.

@GigaOrts
Last active March 22, 2024 18:19
Show Gist options
  • Save GigaOrts/96f6a82022ebc282c92d0f2f2a730871 to your computer and use it in GitHub Desktop.
Save GigaOrts/96f6a82022ebc282c92d0f2f2a730871 to your computer and use it in GitHub Desktop.
Countdown
[RequireComponent(typeof(TimerMonobeh))]
public class ClientTimerMonobeh : MonoBehaviour
{
[SerializeField] private int _bonus = 1;
[SerializeField] private float _period = 0.5f;
private int _score;
private TimerMonobeh _timer;
private void Awake()
{
_timer = GetComponent<TimerMonobeh>();
}
private void Update()
{
if (_timer.ElapsedTime >= _period)
{
_score += _bonus;
_timer.ResetElapsedTime();
}
}
private void OnGUI()
{
GUI.color = Color.green;
GUILayout.Label($"Bonus: {_bonus} score in {_period:0.0} sec.");
GUILayout.Label($"Countdown: {_timer.ElapsedTime:0.0}");
GUILayout.Label($"Score: {_score}");
if (GUILayout.Button("SwitchTimer"))
{
SwitchTimer();
}
}
private void SwitchTimer()
{
if (_timer.IsRunning)
_timer.Pause();
else
_timer.Run();
}
}
public class TimerMonobeh : MonoBehaviour
{
public bool IsRunning { get; private set; }
public float ElapsedTime { get; private set; }
public void Run()
{
IsRunning = true;
StartCoroutine(Countdown());
}
public void Pause()
{
IsRunning = false;
}
public void ResetElapsedTime()
{
ElapsedTime = default;
}
private IEnumerator Countdown()
{
while (IsRunning)
{
ElapsedTime += Time.deltaTime;
yield return null;
}
}
}
public class ClientTimer : MonoBehaviour
{
[SerializeField] private int _bonus = 1;
[SerializeField] private float _period = 0.5f;
private int _score;
private Timer _timer;
private void Awake()
{
_timer = new Timer();
}
private void Update()
{
if (_timer.IsRunning == false)
return;
_timer.Countdown(Time.deltaTime);
if (_timer.ElapsedTime >= _period)
{
_score += _bonus;
_timer.Reset();
}
}
private void OnGUI()
{
GUILayout.Label($"Bonus: {_bonus} score in {_period:0.0} sec.");
GUILayout.Label($"Countdown: {_timer.ElapsedTime:0.0}");
GUILayout.Label($"Score: {_score}");
if (GUILayout.Button("SwitchTimer"))
{
SwitchTimer();
}
}
private void SwitchTimer()
{
if (_timer.IsRunning)
_timer.Pause();
else
_timer.Run();
}
}
public class Timer
{
public bool IsRunning { get; private set; }
public float ElapsedTime { get; private set; }
public void Countdown(float deltaTime)
{
if (IsRunning == false)
return;
ElapsedTime += deltaTime;
}
public void Run()
{
IsRunning = true;
}
public void Pause()
{
IsRunning = false;
}
public void Reset()
{
ElapsedTime = default;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment