Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
2
Question by TheMustang7 · May 23, 2014 at 10:34 AM · c#androidsystemlife

How can i make a life system like candy crush?

Hello every one, i'm a french developper so forgive my english please! I'm working on an app for android in unity and i need help with my code. I want to make a life system like candy crush, a system that give you a pack of life after 12 hours in real life but sometimes my code works and sometimes not and i don't know why. There is my code (i give life every 3 minutes in this code just for testing):

using UnityEngine; using System.Collections; using System;

public class GameHelperScript : MonoBehaviour {

 public int Playerlife;
 DateTime oldDate;
 DateTime currentDate;
 int hours;

 void Start()
 {
     if (PlayerPrefs.GetInt("FirstStart") == 0)
     {
         PlayerPrefs.SetInt("FirstStart", 1);
         PlayerPrefs.SetInt("PlayerLife", 5);
         PlayerPrefs.SetString("sysString", System.DateTime.Now.ToString());
     }

     Playerlife = PlayerPrefs.GetInt("PlayerLife");
 }

 void Update ()
 {
     DateTime.TryParse (PlayerPrefs.GetString ("sysString"), out oldDate);
     currentDate = System.DateTime.Now;
     hours = currentDate.Minute - oldDate.Minute;
     if (hours >= 3)
     {
         PlayerPrefs.SetInt("PlayerLife", 5);
         Playerlife = PlayerPrefs.GetInt("PlayerLife");
         PlayerPrefs.SetString("sysString", System.DateTime.Now.ToString());
     }

     
 }

}

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
9
Best Answer

Answer by NoseKills · May 23, 2014 at 11:54 PM

Your problem probably is here

 hours = currentDate.Minute - oldDate.Minute;

DateTime.Minute means "minutes in this hour". So if the timestamp "sysString" was saved at 12:59 and player continued at 13:03, hours would be -56.

You need to use TimeSpan class to keep track and compare passed time periods. Something like this (just to give you an idea, not directly applicable to your game):

 using UnityEngine;
 using System;
 
 public class test : MonoBehaviour 
 {
     private const int MAX_LIVES = 5;
 
     // 5 seconds for testing
     private static TimeSpan newLifeInterval = new TimeSpan(0,0,5);
 
 
     private DateTime lostLifeTimeStamp;
     private int livesLeft = MAX_LIVES;
     private int amountOfIntervalsPassed;
 
     // Update is called once per frame
     void Update () 
     {
         if (livesLeft < MAX_LIVES)
         {
             TimeSpan t = DateTime.Now - lostLifeTimeStamp;
 
             // in theory if you wait for many many years, amountOfIntervalsPassed might be bigger than fits in an int 
             try 
             {
                 // round down or we get a new life whenever over half of interval has passed
                 double intervalD = System.Math.Floor(t.TotalSeconds / newLifeInterval.TotalSeconds);
                 amountOfIntervalsPassed = Convert.ToInt32(intervalD);
             }
             catch (OverflowException) 
             {
 // something has probably gone wrong. give full lives. normalize the situation
                 livesleft = MAX_LIVES;
             }   
 
             if (amountOfIntervalsPassed + livesLeft >= MAX_LIVES)
             {
                 livesLeft = MAX_LIVES;
             }
 
             Debug.Log("it's been " + t + " since lives dropped from full (now "+livesLeft+"). " + amountOfIntervalsPassed + " reloads passed. Lives Left: " + getAmountOfLives() );
         }
     }
 
     [ContextMenu ("Lose Life")]
     void lostLife()
     {
         if (livesLeft-- == MAX_LIVES)
         {
             // mark the timestamp only when lives drop from MAX to MAX -1
             lostLifeTimeStamp = DateTime.Now;
 
               ///////////////////////////////////////////////////////////////////////////////////
              // SAVE livesLeft AND lostLifeTimeStamp HERE AND RESTORE WHEN STARTING THE GAME ///
             ///////////////////////////////////////////////////////////////////////////////////
         }
     }
 
     int getAmountOfLives()
     {
         return Mathf.Min(livesLeft + amountOfIntervalsPassed, MAX_LIVES);
     }
 }
 

If you add the script to a GameObject and run the Scene, you can test losing a life by right clicking on the script in the Inspector view.

Comment
Add comment · Show 8 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image TheMustang7 · May 25, 2014 at 05:41 PM 1
Share

It worked thak you very much it was very helpful!

avatar image tw1st3d · May 25, 2014 at 05:41 PM 1
Share

If this answer was correct, please tick it as answered by clicking the checkmark under the thumbs next to the answer.

avatar image manoj_tanzanite_infotech · Jun 17, 2015 at 03:37 PM 0
Share

$$anonymous$$ay you send me this full scripts please thanx in advance i am new in field of Unity

avatar image NoseKills · Jun 18, 2015 at 10:00 AM 0
Share

There is no "full scripts". This is a made up example i wrote to answer this question.

avatar image zero_null NoseKills · Mar 10, 2016 at 12:38 PM 0
Share

can anyone assure about correctness of this script? Also I am interested in making a timer as well.

avatar image SquigglyFrog zero_null · Mar 10, 2016 at 09:19 PM 0
Share

You can assure it works yourself. Use it, try it, see if it works. if it doesnt modify it to make it work. If you don't know how to code to change it, then it's probably time to learn, or use a prebuilt system like one exa games has on the asset store.

avatar image JRHidalgo · Mar 30, 2016 at 05:01 AM 0
Share

Could someone please help me. I am new to unity3d. I implemented this code Nose$$anonymous$$ills. After I run out of lives, the lives I want to return one by one. but the lives progresibamente not return but return all together after having done all the time.

my goal is that every ten $$anonymous$$utes the player get a life. and the count is at COUNTDOWN. This is the modification of code:

using UnityEngine; using System.Collections; using UnityEngine.UI; using System;

public class SystemLifes : $$anonymous$$onoBehaviour { private const int Life$$anonymous$$ax = 5; public int LifeCount = Life$$anonymous$$ax; //for reasons of testing only add 1 second. private static TimeSpan newLifeTime = new TimeSpan (0,0,1);

 private DateTime lostLifeTimeStamp;    
 private int TimeInterval;        //Each time you pass an interval you should get a life.

 public Text chronometerLives;
 public Text Lifes;            //var numeric counter lives
 

 void Update () {
     Lifes.text = LifeCount.ToString();  // numeric counter lives.

     //This code is only for testing. to increase or decrease lives.
     if (Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.DownArrow)) {
         lostLife();
     }if (Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.UpArrow)) {
         GetLife();
     }
     if (LifeCount < Life$$anonymous$$ax){
         TimeSpan t = DateTime.Now - lostLifeTimeStamp;

         // in theory if you wait for many many years, amountOfIntervalsPassed might be bigger than fits in an int 
     try {
             // round down or we get a new life whenever over half of interval has passed
             double intervalD = System.$$anonymous$$ath.Floor(t.TotalSeconds / newLifeTime.TotalSeconds);
             TimeInterval = Convert.ToInt32(intervalD);
         }
         catch (OverflowException) {
             // something has probably gone wrong. give full lives. normalize the situation
             LifeCount = Life$$anonymous$$ax;
         }   
         if (TimeInterval + LifeCount >= Life$$anonymous$$ax){
             LifeCount = Life$$anonymous$$ax;
         }
         chronometerLives.text = t.ToString ();
         Debug.Log(    "Has been " + t + " the time until complete lives. (lives today "+LifeCount+")
                     . " + TimeInterval + " recharged lives. lives: " + getAmountOfLives() );
     }
 }

 
 public void GetLife(){
     LifeCount++;
 }
 [Context$$anonymous$$enu ("Perder Vida")]
 void lostLife()    {
     if (LifeCount-- == Life$$anonymous$$ax){
         // mark the timestamp only when lives drop from $$anonymous$$AX to $$anonymous$$AX -1
         lostLifeTimeStamp = DateTime.Now;

         // SAVE livesLeft AND lostLifeTimeStamp HERE AND RESTORE WHEN STARTING THE GA$$anonymous$$$$anonymous$$
     }
 }

 int getAmountOfLives(){
     return $$anonymous$$athf.$$anonymous$$in(LifeCount + TimeInterval, Life$$anonymous$$ax);
 }

}

//This image is the result of this code. https://www.dropbox.com/s/iyt4p47b33462rn/LifeSystem.gif?dl=0

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

29 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

TimeZoneInfo.GetSystemTimeZones().Count gives 0 for unity android app 0 Answers

Unity 3d - connect android to pc via usb 0 Answers

Unity Ads currently playing ads repeatedly, how to fix? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges