- Home /
Send notification when ur energy has full
i am currently developing a mobile game that has a energy system feature (similar to candy crush saga life system) where it regenerates energy every certain time. i can make the energy regenerates using System.timers.timer. Even when the game stop, the time still runs which what i need. also i have bought an asset called ELAN Manager which can send local notification in android device. here is the code
using UnityEngine; using System.Collections; using System; using System.Timers; public class RegenEnergy : MonoBehaviour { private static System.Timers.Timer aTimer; DateTime oldDate; DateTime currentDate; DateTime lastDate;
public int maxEnergy;
private int energyGiven;
public int energy;
private int energyTick;
public static int secondTimePlaying;
private GameObject[] energyArray;
public ELANNotification notification;
void Awake () {
energyArray = GameObject.FindGameObjectsWithTag ("Resource");
if (energyArray.Length <= 1) {
DontDestroyOnLoad(gameObject);
}
else {
DestroyObject(gameObject);
}
}
void Start ()
{
PlayerPrefs.DeleteAll ();
DontDestroyOnLoad (gameObject);
secondTimePlaying = PlayerPrefs.GetInt ("SecondTimePlaying");
notification.title = "Full Energy";
notification.message = "Your energy has full! Come play Mahabharat War!";
if (secondTimePlaying == 0) {
energy = 0;
energyGiven = 0;
energyTick = energy;
oldDate = System.DateTime.Now;
}
else {
energy = PlayerPrefs.GetInt("Energy");
energyGiven = 0;
lastDate = Convert.ToDateTime(PlayerPrefs.GetString ("CloseTime"));
oldDate = System.DateTime.Now;
TimeSpan span = oldDate.Subtract ( lastDate );
energy += (int)span.TotalSeconds / 5;
energyTick = energy;
if (energy >= maxEnergy) {
energy = maxEnergy;
}
GameObject.Find("ContainerNext/EnergyText").GetComponent<TextMesh>().text = energy.ToString ()+"/"+maxEnergy;
}
aTimer = new System.Timers.Timer(5 * 1000);
aTimer.Elapsed += new ElapsedEventHandler(OnTick);
aTimer.Stop ();
}
private void OnTick(object source, ElapsedEventArgs e) {
energyTick += 1;
Debug.Log (energyTick);
if (energyTick >= maxEnergy) {
energyTick = maxEnergy;
notification.send();
//aTimer.Stop ();
}
}
void OnApplicationQuit() {
PlayerPrefs.SetString ("CloseTime", currentDate.ToString());
PlayerPrefs.SetInt ("Energy", energy);
PlayerPrefs.SetInt ("SecondTimePlaying", 1);
aTimer.Start();
energyTick = energy;
}
void Update()
{
currentDate = System.DateTime.Now;
TimeSpan span = currentDate.Subtract ( oldDate );
if(span.TotalSeconds/5 > energyGiven) {
energy++;
energyGiven++;
if (energy >= maxEnergy) {
energy = maxEnergy;
}
}
GameObject.Find("ContainerNext/EnergyText").GetComponent<TextMesh>().text = energy.ToString ()+"/"+maxEnergy;
}
} In the onTick method i have set that whenever energy is max, it send notification to user that energy has full even though the app is closed. (I have tried in editor using debug.log ("ur energy has full") and when i stop the game, the energy still increasing and when it reach max it will show ur energy has full.) The problem is when i run the app on real android device, when the energy has maxed the notification does not work but when i put the notification.send() in update, it works. Can someone tell me what's wrong with my code?
Answer by okiwanben0bi · Oct 30, 2014 at 07:21 PM
It seems that you are sending the Notification all the time. That could be an overload.
This lines:
if (energyTick >= maxEnergy) {
energyTick = maxEnergy;
notification.send();
//aTimer.Stop ();
}
You are calling it all the time because >= instead of > in the if.
Here's the right one:
if (energyTick > maxEnergy) {
energyTick = maxEnergy;
notification.send();
//aTimer.Stop ();
}
If energyTick runs along after that, you need to do that another way.
whereelse: desired energyTick=maxEnergy / outside energyTick++ / undesired energyTick=maxEnergy / outside energyTick++ / undesired energyTick=maxEnergy etc etc etc.
You should use something like that:
protected bool gameHasStoppedOnce=false; // everytime the game starts, it's set to false.
if (energyTick > maxEnergy && !gameHasStoppedOnce)
{
energyTick=maxEnergy;
gameHasStoppedOnce=true;
..etc..
} // and stop energyTick from getting +x outside, else the energyTick=maxEnergy is not usefull at all!
Hope that solves the Problem.
Answer by saddam751 · Aug 12, 2015 at 06:55 AM
Hello , I am using code below for life functionality like candy crush but it is not giving desirable results-
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Text;
using System;
public class LifeFunctionality : MonoBehaviour
{
//For Life Functionality
private bool isPause = true;
public Text lifeText;
DateTime currentDate;
DateTime oldDate;
private long temp;
private float StartTime;
public static int LifeCounter;
private int TimeDifference;
public int timeToAdd;
private int dividesTimeToAddAfterResume;
public GameObject pauseButton;
public GameObject resumeButton;
private float differencePlusRemainingTime;
private float totalDifferenceInSeconds;
void Start()
{
PlayerPrefs.DeleteAll();
//GAME STARTED FIRST TIME SET LIFE COUNTER TO 0
if (!(PlayerPrefs.HasKey ("LifeCounter")))
{
LifeCounter=0;
}
else if ((PlayerPrefs.HasKey ("LifeCounter")))
{
LifeCounter=PlayerPrefs.GetInt("LifeCounter");
}
//GAME PLAYER FIRST TIME AND THERE IS NO SCENE SWITCHING
if (!(PlayerPrefs.HasKey ("RunningGameTimeToAdd")))
{
timeToAdd = 0;
StartTime = Time.timeSinceLevelLoad;
}
//IF SCENE SWITCHING OCCURED , WE ARE STORING THE TIME IN timetoadd INT AND UPDATING LIFE COUNTER
else if ((PlayerPrefs.HasKey ("RunningGameTimeToAdd")))
{
LifeCounter=PlayerPrefs.GetInt("LifeCounter");
StartTime = Time.timeSinceLevelLoad;
timeToAdd=(PlayerPrefs.GetInt("RunningGameTimeToAdd"));
Debug.Log("Remaining Time On Scene Switching-Level-1------->"+ timeToAdd);
}
}
void FixedUpdate()
{
// Debug.Log((int)Time.timeSinceLevelLoad);
TimeDifference = (int)((Time.timeSinceLevelLoad+timeToAdd) - StartTime);
/* Debug.Log("totalDifferenceInSeconds---->"+totalDifferenceInSeconds);
Debug.Log("timeToAdd---->"+timeToAdd);
Debug.Log("ADD---->"+(totalDifferenceInSeconds +timeToAdd));
// Debug.Log("Time.Time---->"+(int)Time.timeSinceLevelLoad);
// Debug.Log("StartTime---->"+StartTime);
Debug.Log("Time Difference---->"+TimeDifference);*/
if (TimeDifference >= 10)
{
timeToAdd = 0;
StartTime = Time.timeSinceLevelLoad;
if(LifeCounter < 5)
{
LifeCounter += 1;
// Debug.Log("LIFE==="+LifeCounter);
}
}
lifeText.text =""+LifeCounter;
}
//THIS IS CALLED WHEN GAME IS RESUMED FROM PAUSE
void CalculateTimeDifference()
{
//Store the current time when it starts
currentDate = System.DateTime.Now;
Debug.Log("Current Date----->"+currentDate);
//Grab the old time from the player prefs as a long
long temp = Convert.ToInt64(PlayerPrefs.GetString("TimeSpent_OnApplicationPause"));
//Convert the old time from binary to a DataTime variable
DateTime oldDate = DateTime.FromBinary(temp);
print("oldDate: " + oldDate);
//Use the Subtract method and store the result as a timespan variable
TimeSpan difference = currentDate.Subtract(oldDate);
print("Difference: " + difference);
string highestPriority = difference.ToString();
//Debug.Log(highestPriority);
String[] priorityCache= highestPriority.Split(":"[0]);
int getHour;
getHour=(int.Parse(priorityCache[0]));
int hoursInSec;
hoursInSec=getHour*3600;
Debug.Log("getHour----------> "+getHour);
Debug.Log("hoursInSec----------> "+hoursInSec);
int getMin;
getMin=(int.Parse(priorityCache[1]));
int minInSec;
minInSec=getMin*60;
Debug.Log("getMin----------> "+getMin);
Debug.Log("minInSec----------> "+getMin);
float getSec;
getSec=((int)float.Parse(priorityCache[2]));
Debug.Log("getSec---------->"+getSec);
totalDifferenceInSeconds=(int)(hoursInSec + minInSec + getSec);
Debug.Log("TOTAL DIFFERENCE IN SECONDS---->"+totalDifferenceInSeconds);
differencePlusRemainingTime=(int)(PlayerPrefs.GetInt("RunningGameTimeToAdd") + totalDifferenceInSeconds);
Debug.Log("TOTAL DIFFERENCE PLUS REMAINING TIME---->"+differencePlusRemainingTime);
timeToAdd = (int)(differencePlusRemainingTime % 10);
Debug.Log("TIME TO ADD AFTER RESUME---------> "+timeToAdd);
if(LifeCounter < 5)
{
LifeCounter += (int)(differencePlusRemainingTime / 10);
Debug.Log("RESUME----> "+LifeCounter);
if(LifeCounter > 5)
{
LifeCounter = 5;
}
}
}
/* void OnApplicationQuit()
{
//Save the current system time as a string in the player prefs class
}*/
public void loadLevel1()
{
PlayerPrefs.SetInt("RunningGameTimeToAdd", TimeDifference);
Debug.Log("RunningGameTimeToAdd------>"+PlayerPrefs.GetInt("RunningGameTimeToAdd"));
PlayerPrefs.SetInt("LifeCounter",LifeCounter);
Debug.Log("Remaining Time On Scene Switching------->"+ PlayerPrefs.GetInt("RunningGameTimeToAdd"));
Application.LoadLevel("Scene1");
}
public void loadLevel2()
{
PlayerPrefs.SetInt("RunningGameTimeToAdd", TimeDifference);
PlayerPrefs.SetInt("LifeCounter",LifeCounter);
Debug.Log("Remaining Time On Scene Switching------->"+ PlayerPrefs.GetInt("RunningGameTimeToAdd"));
Application.LoadLevel("Scene2");
}
public void quitPressed()
{
PlayerPrefs.SetInt("RunningGameTimeToAdd", TimeDifference);
PlayerPrefs.SetInt("LifeCounter",LifeCounter);
Debug.Log("Remaining Time On Scene Switching------->"+ PlayerPrefs.GetInt("RunningGameTimeToAdd"));
Application.LoadLevel("Home");
}
public void level1()
{
PlayerPrefs.SetInt("RunningGameTimeToAdd", TimeDifference);
PlayerPrefs.SetInt("LifeCounter",LifeCounter);
Application.LoadLevel("Scene1");
}
public void level2()
{
PlayerPrefs.SetInt("RunningGameTimeToAdd", TimeDifference);
PlayerPrefs.SetInt("LifeCounter",LifeCounter);
Debug.Log("Remaining Time On Scene Switching------->"+ PlayerPrefs.GetInt("RunningGameTimeToAdd"));
Application.LoadLevel("Scene2");
}
public void pauseGame()
{
PlayerPrefs.SetString("TimeSpent_OnApplicationPause", System.DateTime.Now.ToBinary().ToString());
PlayerPrefs.SetInt("RunningGameTimeToAdd", TimeDifference);
Debug.Log("Remaining Time On Scene Switching------->"+ PlayerPrefs.GetInt("RunningGameTimeToAdd"));
PlayerPrefs.SetInt("LifeCounter",LifeCounter);
resumeButton.SetActive(true);
pauseButton.SetActive(false);
Time.timeScale=0;
}
public void ResumeGame()
{
LifeCounter=PlayerPrefs.GetInt("LifeCounter");
if(PlayerPrefs.HasKey("TimeSpent_OnApplicationPause"))
CalculateTimeDifference();
pauseButton.SetActive(true);
resumeButton.SetActive(false);
Time.timeScale=1;
}
}