简体   繁体   中英

Unity3d Real time counter in background

I am making a game that will have energy bar.
The bar will have maximum of 25 energy. When user consumes energy, every "point" should refill in 3 minutes (from empty to full energy bar 25x3min=75min).

Now, how can I implement a timer that will count in every scene, and even when game is closed?

Thank you.

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

Note that in Unity specifically, https://docs.unity3d.com/ScriptReference/Time-realtimeSinceStartup.html is available for this purpose. Otherwise...


If you want to 'count when the game is closed', then you will have to work from the system clock rather than (say) Time.time or similar.

So, you'll need to check the time every now and then, and when you do this, calculate the elapsed time between now and the last time you checked.

Then multiply this by a top-up factor, add this to your energy level and store the current time.

Get the current time in seconds like this...

DateTime epochStart = new System.DateTime(1970, 1, 1, 8, 0, 0, System.DateTimeKind.Utc);

double timestamp = (System.DateTime.UtcNow - epochStart).TotalSeconds;

... so your code fragment doing all this work might look like:

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;

}

(Please note, this compiles, but I've not checked it properly, hopefully you get the gist!)

Also, you'll need to save the LastTimeChecked variable to disk and reload it between runs so the energy can accumulate while the game isn't running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM