Unity3d后台实时计数器



我正在制作一款带有能量条的游戏
酒吧将有最大25能量。当用户消耗能量时,每个"点"应在3分钟内重新填充(从空能量棒到满能量棒25x3min=75min)。

现在,我如何实现一个计时器,它将在每个场景中计数,甚至在游戏关闭时也会计数?

谢谢。

我认为最好的方法是使用实际时间,将开始时间保存在外部文件中,并在游戏再次开始时重新计算能量水平。

请注意,在Unity中,https://docs.unity3d.com/ScriptReference/Time-realtimeSinceStartup.html可用于此目的。否则


如果你想"计算游戏何时结束",那么你必须从系统时钟开始工作,而不是(比如)Time.Time或类似的时钟。

因此,您需要不时检查时间,当您这样做时,计算从现在到上次检查之间的经过时间。

然后将其乘以一个补充因子,将其添加到你的能量水平中,并存储当前时间。

以秒为单位获取当前时间,如下所示。。。

DateTime epochStart = new System.DateTime(1970, 1, 1, 8, 0, 0, System.DateTimeKind.Utc);
double timestamp = (System.DateTime.UtcNow - epochStart).TotalSeconds;

因此,完成所有这些工作的代码片段可能看起来像:

double LastTimeChecked = 0;
double EnergyAccumulator;
int Energy;
const double EnergyRefillSpeed = 1 / (60*3);
const int EnergyMax = 25;
double TimeInSeconds()
{
    DateTime epochStart = new System.DateTime(1970, 1, 1, 8, 0, 0, System.DateTimeKind.Utc);
    double timestamp = (System.DateTime.UtcNow - epochStart).TotalSeconds;
    return timestamp;
}
// call this whenever you can!
void update()
{
    double TimeNow = TimeInSeconds();
    double TimeDelta = 0;
    // if we have updated before...
    if( LastTimeChecked != 0 )
    {
        // get the time difference between now and last time
        TimeDelta = TimeNow - LastTimeChecked;
        // multiply by our factor to increase energy.
        EnergyAccumulator += TimeDelta * EnergyRefillSpeed;
        // get the whole points accumulated so far
        int EnergyInt = (int) EnergyAccumulator;
        // remove the whole points we've accumulated
        if( EnergyInt > 0 )
        {
            Energy += EnergyInt;
            EnergyAccumulator -= EnergyInt;
        }
        // cap at the maximum
        if( Energy > EnergyMax )
            Energy = EnergyMax;
    }
    // store the last time we checked
    LastTimeChecked = TimeNow;
}

(请注意,这是编译的,但我没有正确检查,希望你能理解要点!)

此外,您需要将LastTimeChecked变量保存到磁盘上,并在两次运行之间重新加载,以便在游戏不运行时积累能量。

最新更新