Life System in Unity

Life System in Unity

We all must have played games in which we need lives to continue playing. Some of these games include Candy Crush Saga, Candy Crush Soda and so on. Every unity developer would have made; or would need to make a life system in their development career. So, let us learn to create a life system in Unity in an easy way.

The important parameters in creating the life system are
– the maximum number of lives a player can get,
– the time in which a life replenishes , and
– a counter that keeps track of the number of lives the player has

    //The max lives that a player can have, let us take 5
    int maxLives = 5;

    //Each life replenishes in 15minutes or 900 seconds
    float lifeReplenishTime = 900f;

    // The number of lives that the player has
    int _lives;
    public int lives{
        set {
            _lives = value; 
            PlayerPrefs.SetInt("Lives", _lives);
        }
        get {
            return _lives;
        }
    }

Now, we need a counter that determines the time lapsed:

    public double timerForLife;

We update the parameter timerForLife in the Update function.

private void Update()
 {
        // life counter needs update only if lives are less than maxLives
        if (lives < maxLives)
        {
            timerForLife += Time.deltaTime;
            //when timerForLife becomes greater than 900sec, we update a life
            if (timerForLife > lifeReplenishTime)
            {
                lives++; //you get a life after 15 minutes
                //It is advised to use UpdateLives(timerForLife) here instead of lives++;
            }
        }
 }

    //PlayerPref "LifeUpdateTime" stores the value in string of the time when the life counter lives was last updated
    void UpdateLives(double timerToAdd ){
        if (lives < maxLives)
        {
            int livesToAdd = Mathf.FloorToInt((float)timerToAdd / lifeReplenishTime);
            timerForLife = (float)timerToAdd % lifeReplenishTime;
            lives += livesToAdd;
            if (lives > maxLives)
            {
                lives = maxLives;
                timerForLife = 0;
            } 
        }
        PlayerPrefs.SetString("LifeUpdateTime", DateTime.Now.ToString());
    }

We have now created a basic life system. But we also need the lives to replenish even when the game is shut or running in background. So that whenever the player relaunches the game, he gets his updated lives.

Update the life counter in Unity when the app goes to background

For this, we need to save the time at which the app goes to background. We will make use of the OnApplicationPause function of Unity.

DateTime  timeOfPause;
void OnApplicationPause(bool isPause){
        if (isPause)
        {
            //save the system time at which the application went in background 
            timeOfPause = System.DateTime.Now;
        }
        else
        {
            if(timeOfPause == default(DateTime)){
                timeOfPause = System.DateTime.Now;
            }
            float timerToAdd = (float)(System.DateTime.Now - timeOfPause).TotalSeconds;
            timerForLife += timerToAdd;
            UpdateLives(timerForLife);
        }
    }

Update the life counter in Unity whenever the game is relaunched

We update the life counter in the Awake function

    void Awake () {
      
        if(!PlayerPrefs.HasKey("Lives")){
            PlayerPrefs.SetString("LifeUpdateTime", DateTime.Now.ToString());
        }
        lives = PlayerPrefs.GetInt("Lives", maxLives);

        //update life counter only if lives are less than maxLives
        if (lives < maxLives)
        {
            //timerToAdd calculates the time lapsed till since the game was last shut down
            float timerToAdd = (float)(System.DateTime.Now - Convert.ToDateTime(PlayerPrefs.GetString("LifeUpdateTime"))).TotalSeconds;
            //update life counter depending upon how much time has been lapsed
            UpdateLives(timerToAdd);
        }
    }

Display the time left for a new life

    public string showLifeTimeInMinutes()
    {
        float timeLeft = lifeReplenishTime - (float)timerForLife;
        int min = Mathf.FloorToInt(timeLeft / 60);
        int sec = Mathf.FloorToInt(timeLeft % 60);
        return min + ":" + sec.ToString("00");
    }

In the similar way, you can calculate the timer for creating and upgrading buildings, upgrading troops, etc in games like Clash of Clans.

One problem that the developer faces in creating a life system in Unity is that the player tends to changes the system time (time of his device) in order to gain life. To overcome this issue, it is advised to fetch the time from server instead of using System.DateTime.Now.

If you have any queries, feel free to comment.

Happy Coding!

Share This Post

Post Comment