Hello
im new to both C# and unity. And was wondering how i can make a timer that starts at 10min then when that time is done counting down a new timer with 5min starts. And then it goes back and forth like that for ever. and also have it count down inn minutes not seconds.
Hey!
Here’s a sample script with the implementation you require. I commented the entire script so you could walk through it and understand what’s going on. Hope it helps!
Create a new script named “AlternatingTimer”
using UnityEngine;
using UnityEngine.Events;
// This script alternates between two timers with different durations.
// When one timer finishes, it switches to the other, triggering events for each.
public class AlternatingTimer : MonoBehaviour
{
// Duration of the first (primary) timer in minutes
public float primaryDuration = 10;
// Duration of the second (secondary) timer in minutes
public float secondaryDuration = 5;
public UnityEvent OnPrimaryTimerElapsed; // Triggered when the primary timer ends
public UnityEvent OnSecondaryTimerElapsed; // Triggered when the secondary timer ends
private bool _usePrimaryTime; // Keeps track of which timer is currently active
private float _timeRemaining; // Time remaining in the current timer
private void Start()
{
// Start with the primary timer active
_usePrimaryTime = true;
// Set the time remaining to the duration of the primary timer
_timeRemaining = primaryDuration;
}
private void Update()
{
// Check if there is still time remaining on the current timer
if (_timeRemaining > 0)
{
// Reduce the remaining time by the time that has passed since the last frame
// Divide by 60 to convert from seconds to minutes
_timeRemaining -= Time.deltaTime / 60f;
}
else
{
// If the timer runs out, trigger the corresponding event
if (_usePrimaryTime)
{
OnPrimaryTimerElapsed?.Invoke(); // Trigger the primary timer event if it's the primary timer
}
else
{
OnSecondaryTimerElapsed?.Invoke(); // Trigger the secondary timer event if it's the secondary timer
}
// Switch to the other timer
SwitchTimer();
}
}
// This method switches between the primary and secondary timers
private void SwitchTimer()
{
// Toggle between primary and secondary timers
_usePrimaryTime = !_usePrimaryTime;
// Set the remaining time to the duration of the new active timer
if (_usePrimaryTime)
{
_timeRemaining = primaryDuration; // Switch to primary timer
}
else
{
_timeRemaining = secondaryDuration; // Switch to secondary timer
}
}
}
Thank you som much
helped me out a LOT!
