Friday, February 20, 2015

idle game timer tutorial

Below is a simple idle game timer tutorial for Unity

1. When the user browse away or exit the game, you need to save the current time immediately 


/////////////////////////////////////////////////////////
void savegame(){
    System.DateTime epochStart = new System.DateTime(197011000System.DateTimeKind.Utc);
        curtime = (int)(System.DateTime.UtcNow - epochStart).TotalSeconds;
        
        PlayerPrefs.SetInt("curtime",curtime);

}
///////////////////////////////////////////////////////////

the above function is a save function where you save the time using "epoch time" meaning how many seconds since year 1970, so you can save it into the integer variable "curtime"

example 1424451609

When the user load the game, you do as below

///////////////////////////////////////////////////////////
void loadgame()
{


loadtime = PlayerPrefs.GetInt("curtime");

        System.DateTime epochStart = new System.DateTime(197011000System.DateTimeKind.Utc);
        curtime = (int)(System.DateTime.UtcNow - epochStart).TotalSeconds;



        int exit_duration;

        exit_durationcurtime - loadtime;
        

   

}
///////////////////////////////////////////////////////////

So when you load the game back, you get the curtime using epoch way then you get the loadtime from your saved, so you can calculate out the exit duration

example, the user exit game on
1424451609 (loadtime)

then he come back on
1424451629 (curtime)

So you know he exit for 20 seconds, and you take this to apply to your games accordingly

///////////////////////////////////////////////////////
void OnApplicationFocus(bool focusStatus
{
        //focus status 1 mean pause
        if(focusStatus==false)
        {
            Debug.Log ("pause");
            savegame();
        }
        if(focusStatus==true)
        {
            Debug.Log ("unpause");
            loadgame();

        }
}
///////////////////////////////////////////////////////

So in unity, you need to save the game when the user lose focus, because maybe he is playing other app, or the phone is auto close, then you save the game, then when he come back, load the game back and apply the "exit_duration" you calculated to your game




No comments:

Post a Comment