Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Join us on Dec 8, 2022, between 7 am & 7 pm EST, in the DOTS Dev Blitz Day 2022 - Q&A forum, Discord, and Unity3D Subreddit to learn more about DOTS directly from the Unity Developers.
    Dismiss Notice
  3. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice

Lives system like in Candy Crush Saga

Discussion in 'Scripting' started by isacan, Dec 4, 2014.

  1. isacan

    isacan

    Joined:
    Jul 18, 2013
    Posts:
    37
    I am trying to implement a lives system in Candy Crush Saga where if you run out of lives then in 30 minutes they will regenerate. Here is the code I have so far. So, what I am doing is taking the current time of when the user runs out of lives. Then the next time they open the app I see what the time is and check to see if 30 minutes have elapsed and then refill the lives.


    How can implement like this?
     
  2. dterbeest

    dterbeest

    Joined:
    Mar 23, 2012
    Posts:
    386
  3. isacan

    isacan

    Joined:
    Jul 18, 2013
    Posts:
    37
    Could you describe in more detail?
     
  4. Sbizz

    Sbizz

    Joined:
    Oct 2, 2014
    Posts:
    250
    He gives you the documentation.

    However, be careful with PlayerPrefs, it is editable by anyone.
     
  5. dterbeest

    dterbeest

    Joined:
    Mar 23, 2012
    Posts:
    386
    Yes, a better aproach would be to create a client-server architecture where this kind of values are stored on the server. That way there is less fraud, but i can imagine that for a simple solution PlayerPrefs works great.

    You could also consider storing the time as an encrypted string, so that it is more difficult to cheat
     
  6. saddam751

    saddam751

    Joined:
    Nov 6, 2013
    Posts:
    41
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.UI;
    4. using System.Text;
    5. using System;
    6. public class LifeFunctionality : MonoBehaviour
    7. {
    8.      //For Life Functionality
    9.      private bool isPause = true;
    10.      public Text lifeText;
    11.    
    12.      DateTime currentDate;
    13.      DateTime oldDate;
    14.    
    15.      private long temp;
    16.      private float StartTime;
    17.      public static int LifeCounter;
    18.      private int TimeDifference;
    19.      public int timeToAdd;
    20.      private int dividesTimeToAddAfterResume;
    21.      public GameObject pauseButton;
    22.      public GameObject resumeButton;
    23.      private float differencePlusRemainingTime;
    24.      private float totalDifferenceInSeconds;
    25.    
    26.      void Start()
    27.      {
    28.          PlayerPrefs.DeleteAll();
    29.          //GAME STARTED FIRST TIME SET LIFE COUNTER TO 0
    30.          if (!(PlayerPrefs.HasKey ("LifeCounter")))
    31.          {
    32.              LifeCounter=0;
    33.          }
    34.          else if ((PlayerPrefs.HasKey ("LifeCounter")))
    35.          {
    36.              LifeCounter=PlayerPrefs.GetInt("LifeCounter");
    37.          }
    38.          //GAME PLAYER FIRST TIME AND THERE IS NO SCENE SWITCHING
    39.          if (!(PlayerPrefs.HasKey ("RunningGameTimeToAdd")))
    40.          {
    41.              timeToAdd = 0;
    42.              StartTime = Time.timeSinceLevelLoad;
    43.          }
    44.          //IF SCENE SWITCHING OCCURED , WE ARE STORING THE TIME IN timetoadd INT AND UPDATING LIFE COUNTER
    45.          else if ((PlayerPrefs.HasKey ("RunningGameTimeToAdd")))
    46.          {
    47.              LifeCounter=PlayerPrefs.GetInt("LifeCounter");
    48.              StartTime = Time.timeSinceLevelLoad;
    49.              timeToAdd=(PlayerPrefs.GetInt("RunningGameTimeToAdd"));
    50.              Debug.Log("Remaining Time On Scene Switching-Level-1------->"+ timeToAdd);
    51.          }
    52.      }
    53.    
    54.    
    55.      void FixedUpdate()
    56.      {
    57.      //    Debug.Log((int)Time.timeSinceLevelLoad);
    58.          TimeDifference = (int)((Time.timeSinceLevelLoad+timeToAdd) - StartTime);
    59.      /*    Debug.Log("totalDifferenceInSeconds---->"+totalDifferenceInSeconds);
    60.          Debug.Log("timeToAdd---->"+timeToAdd);
    61.          Debug.Log("ADD---->"+(totalDifferenceInSeconds +timeToAdd));
    62.      //    Debug.Log("Time.Time---->"+(int)Time.timeSinceLevelLoad);
    63. //        Debug.Log("StartTime---->"+StartTime);
    64.          Debug.Log("Time Difference---->"+TimeDifference);*/
    65.          if (TimeDifference >= 10)
    66.          {
    67.              timeToAdd = 0;
    68.              StartTime = Time.timeSinceLevelLoad;
    69.            
    70.              if(LifeCounter < 5)
    71.              {
    72.                  LifeCounter += 1;
    73. //                Debug.Log("LIFE==="+LifeCounter);
    74.              }
    75.          }
    76.        
    77.          lifeText.text =""+LifeCounter;
    78.      }
    79.    
    80.      //THIS IS CALLED WHEN GAME IS RESUMED FROM PAUSE
    81.      void CalculateTimeDifference()
    82.      {
    83.          //Store the current time when it starts
    84.          currentDate = System.DateTime.Now;
    85.          Debug.Log("Current Date----->"+currentDate);
    86.        
    87.          //Grab the old time from the player prefs as a long
    88.          long temp = Convert.ToInt64(PlayerPrefs.GetString("TimeSpent_OnApplicationPause"));
    89.        
    90.          //Convert the old time from binary to a DataTime variable
    91.          DateTime oldDate = DateTime.FromBinary(temp);
    92.          print("oldDate: " + oldDate);
    93.        
    94.          //Use the Subtract method and store the result as a timespan variable
    95.          TimeSpan difference = currentDate.Subtract(oldDate);
    96.          print("Difference: " + difference);
    97.        
    98.          string highestPriority = difference.ToString();
    99.          //Debug.Log(highestPriority);
    100.        
    101.          String[] priorityCache= highestPriority.Split(":"[0]);
    102.        
    103.          int getHour;
    104.          getHour=(int.Parse(priorityCache[0]));
    105.          int hoursInSec;
    106.          hoursInSec=getHour*3600;
    107.          Debug.Log("getHour----------> "+getHour);
    108.          Debug.Log("hoursInSec----------> "+hoursInSec);
    109.        
    110.          int getMin;
    111.          getMin=(int.Parse(priorityCache[1]));
    112.          int minInSec;
    113.          minInSec=getMin*60;
    114.          Debug.Log("getMin----------> "+getMin);
    115.          Debug.Log("minInSec----------> "+getMin);
    116.          float getSec;
    117.          getSec=((int)float.Parse(priorityCache[2]));
    118.          Debug.Log("getSec---------->"+getSec);
    119.          totalDifferenceInSeconds=(int)(hoursInSec + minInSec + getSec);
    120.          Debug.Log("TOTAL DIFFERENCE IN SECONDS---->"+totalDifferenceInSeconds);
    121.          differencePlusRemainingTime=(int)(PlayerPrefs.GetInt("RunningGameTimeToAdd") + totalDifferenceInSeconds);
    122.          Debug.Log("TOTAL DIFFERENCE PLUS REMAINING TIME---->"+differencePlusRemainingTime);
    123.          timeToAdd = (int)(differencePlusRemainingTime % 10);
    124.          Debug.Log("TIME TO ADD AFTER RESUME---------> "+timeToAdd);
    125.          if(LifeCounter < 5)
    126.          {
    127.              LifeCounter += (int)(differencePlusRemainingTime / 10);
    128.              Debug.Log("RESUME----> "+LifeCounter);
    129.              if(LifeCounter > 5)
    130.              {
    131.                  LifeCounter = 5;
    132.              }
    133.          }
    134.      }
    135. /*    void OnApplicationQuit()
    136.      {
    137.          //Save the current system time as a string in the player prefs class
    138.      }*/
    139.      public void loadLevel1()
    140.      {
    141.          PlayerPrefs.SetInt("RunningGameTimeToAdd", TimeDifference);
    142.          Debug.Log("RunningGameTimeToAdd------>"+PlayerPrefs.GetInt("RunningGameTimeToAdd"));
    143.          PlayerPrefs.SetInt("LifeCounter",LifeCounter);
    144.        
    145.          Debug.Log("Remaining Time On Scene Switching------->"+ PlayerPrefs.GetInt("RunningGameTimeToAdd"));
    146.          Application.LoadLevel("Scene1");
    147.      }
    148.      public void loadLevel2()
    149.      {
    150.          PlayerPrefs.SetInt("RunningGameTimeToAdd", TimeDifference);
    151.          PlayerPrefs.SetInt("LifeCounter",LifeCounter);
    152.          Debug.Log("Remaining Time On Scene Switching------->"+ PlayerPrefs.GetInt("RunningGameTimeToAdd"));
    153.          Application.LoadLevel("Scene2");
    154.      }
    155.      public void quitPressed()
    156.      {
    157.          PlayerPrefs.SetInt("RunningGameTimeToAdd", TimeDifference);
    158.          PlayerPrefs.SetInt("LifeCounter",LifeCounter);
    159.          Debug.Log("Remaining Time On Scene Switching------->"+ PlayerPrefs.GetInt("RunningGameTimeToAdd"));
    160.          Application.LoadLevel("Home");
    161.      }
    162.      public void level1()
    163.      {
    164.          PlayerPrefs.SetInt("RunningGameTimeToAdd", TimeDifference);
    165.          PlayerPrefs.SetInt("LifeCounter",LifeCounter);
    166.        
    167.          Application.LoadLevel("Scene1");
    168.      }
    169.      public void level2()
    170.      {
    171.          PlayerPrefs.SetInt("RunningGameTimeToAdd", TimeDifference);
    172.          PlayerPrefs.SetInt("LifeCounter",LifeCounter);
    173.        
    174.          Debug.Log("Remaining Time On Scene Switching------->"+ PlayerPrefs.GetInt("RunningGameTimeToAdd"));
    175.          Application.LoadLevel("Scene2");
    176.      }
    177.      public void pauseGame()
    178.      {
    179.          PlayerPrefs.SetString("TimeSpent_OnApplicationPause", System.DateTime.Now.ToBinary().ToString());
    180.          PlayerPrefs.SetInt("RunningGameTimeToAdd", TimeDifference);
    181.          Debug.Log("Remaining Time On Scene Switching------->"+ PlayerPrefs.GetInt("RunningGameTimeToAdd"));
    182.          PlayerPrefs.SetInt("LifeCounter",LifeCounter);
    183.          resumeButton.SetActive(true);
    184.          pauseButton.SetActive(false);
    185.          Time.timeScale=0;
    186.      }
    187.      public void ResumeGame()
    188.      {
    189.          LifeCounter=PlayerPrefs.GetInt("LifeCounter");
    190.          if(PlayerPrefs.HasKey("TimeSpent_OnApplicationPause"))
    191.              CalculateTimeDifference();
    192.          pauseButton.SetActive(true);
    193.          resumeButton.SetActive(false);
    194.          Time.timeScale=1;
    195.      }
    196. }
    197.  
     
  7. saddam751

    saddam751

    Joined:
    Nov 6, 2013
    Posts:
    41
    This is using playerPref,But it is not giving desirable results.
     
  8. Timelog

    Timelog

    Joined:
    Nov 22, 2014
    Posts:
    528
    What is the result at the moment, and what is the expected result?
     
  9. Priyanka-Rajwanshi

    Priyanka-Rajwanshi

    Joined:
    Nov 22, 2013
    Posts:
    8
    check out the following link to understand how to create a life counter in unity http://codesaying.com/life-counter-in-unity/

    In order to calculate the time that was lapsed since you last shut down the game, you should save the last time playerprefs in the function OnApplicationPause and calcuate the timelapsed in the Awake Function.
    Code (CSharp):
    1. void Awake () {
    2.  
    3.      if(!PlayerPrefs.HasKey("Lives")){
    4.          PlayerPrefs.SetString("LifeUpdateTime", DateTime.Now.ToString());
    5.      }
    6.      lives = PlayerPrefs.GetInt("Lives", maxLives);
    7.      //update life counter only if lives are less than maxLives
    8.      if (lives < maxLives)
    9.      {
    10.          float timerToAdd = (float)(System.DateTime.Now - Convert.ToDateTime(PlayerPrefs.GetString("LifeUpdateTime"))).TotalSeconds;
    11.          UpdateLives(timerToAdd);
    12.      }
    13.  
    14. }
    15.  
    16. void UpdateLives(double timerToAdd ){
    17.      if (lives < maxLives)
    18.      {
    19.          int livesToAdd = Mathf.FloorToInt((float)timerToAdd / lifeReplenishTime);
    20.          timerForLife = (float)timerToAdd % lifeReplenishTime;
    21.          lives += livesToAdd;
    22.          if (lives > maxLives)
    23.          {
    24.              lives = maxLives;
    25.              timerForLife = 0;
    26.          }
    27.          PlayerPrefs.SetString("LifeUpdateTime", DateTime.Now.AddSeconds(-timerForLife).ToString());
    28.      }else{
    29.          PlayerPrefs.SetString("LifeUpdateTime", DateTime.Now.ToString());
    30.      }
    31. }
    32. void OnApplicationPause(bool isPause)
    33. {
    34.      if (isPause)
    35.      {
    36.          timeOfPause = System.DateTime.Now;
    37.      }
    38.      else
    39.      {
    40.          if(timeOfPause == default(DateTime)){
    41.              timeOfPause = System.DateTime.Now;
    42.          }
    43.          float timerToAdd = (float)(System.DateTime.Now - timeOfPause).TotalSeconds;
    44.          timerForLife += timerToAdd;
    45.          UpdateLives(timerForLife);
    46.      }
    47. }
     
  10. ArnoldBallard

    ArnoldBallard

    Joined:
    Nov 25, 2022
    Posts:
    1
    you can use apk mod, it will always leave your turn full, that's quite suitable for people who like to spend hours in it like me, hope you will like it.
     
    Last edited: Nov 28, 2022