I'm working on a time system in Unity.
All I want from the system is to update the time every minute in addition to:
- The time update is not affected by the FPS game.
- The time update occurs strictly so that if the duration of the day = 1 minute, the system must finish the passage of the day within 60 seconds.
- Not affecting performance because I will use it on phones.
So I used FixedUpdate
and the time is updated in minutes according to the timeMultiplier
"calculated by the duration of the day".
When I tried the system, I found that the day ends in 59.94 seconds instead of 60 seconds (dayDuration = 1 minute).
Note: Measured by debugging
and Time.time
when hours = 24
I monitored the performance and found that the Fixed Timestep = 0.02 (Time.fixedDeltaTime) and the function (UpdateTime) is called 2998 times per minute instead of 3000 when dayDuration = 1 minute.
and when dayDuration = 0.1 minute the function (UpdateTime) is called 300 times and the day ends in 5.98.
Why does the day pass faster than it should be? or is there a better way to do that?
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TimeManager : MonoBehaviour
{
public static TimeManager Instance { get; private set; }
#region Time Properties
[SerializeField] private float dayDuration = 48f;
[HideInInspector] public float timeMultiplier;
private float elapsedTime;
public int hour, minute, totalMinutes;
#endregion
void Awake()
{
#region Singleton
if (Instance != null && Instance != this)
{
Destroy(this);
}
else
{
Instance = this;
}
#endregion
timeMultiplier = 1440 / dayDuration;
elapsedTime = 0;
}
void FixedUpdate()
{
UpdateTime();
}
void UpdateTime()
{
elapsedTime += Time.fixedDeltaTime * timeMultiplier;
while (elapsedTime > 0)
{
minute++;
elapsedTime -= 60f;
if (minute >= 60)
{
minute = 0;
hour++;
if (hour >= 24)
{
hour = 0;
}
}
totalMinutes = hour * 60 + minute;
}
}
}