Hello, I am teaching myself Unity and C# and I though I would tackle the, what I thought, simple task of creating an energy system like found in many mobile freemium games.
The idea is to have an amount of “energy”. Doing an action consumes a set amount of energy. Energy refills over time automatically.
With some help on Reddit I got the functionlity working, but now I want to create a timer that shows the time left until the next energy will be gained and there I hit a wall and not sure how to do it. I tried converting TimeSpan to string but I do not get the result I want. I hope I can find some help here.
Thanks!
Here is the code I have so far:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class EnergyTest : MonoBehaviour {
public Text remainingEnergy;
public Text timeToNextEnergy;
System.TimeSpan timeRemaining;
public System.Action<System.TimeSpan> OnTimeRemainingUpdate;
long lockTime = 0;
int stamina = 0;
int maxStamina = 20;
System.TimeSpan waitTime = new System.TimeSpan(0,0,5);
public void UseOneStamina(){
if (stamina > 0){
lockTime = System.DateTime.Now.Ticks;
stamina--;
}
}
public void UseFiveStamina(){
if (stamina > 4){
lockTime = System.DateTime.Now.Ticks;
stamina -= 5;
}
}
// Use this for initialization
void Start () {
stamina = maxStamina;
}
// Update is called once per frame
void Update () {
if (lockTime > 0){
while (System.DateTime.Now.Ticks >= lockTime + waitTime.Ticks && stamina < maxStamina){
stamina++;
lockTime += waitTime.Ticks;
}
}
if (OnTimeRemainingUpdate != null)
{
long timeRemainingTicks = lockTime + waitTime.Ticks - System.DateTime.Now.Ticks;
timeRemaining = new System.TimeSpan(timeRemainingTicks);
OnTimeRemainingUpdate(timeRemaining);
}
System.TimeSpan timeToFill = new System.TimeSpan(lockTime);
timeToNextEnergy.text = string.Format("{0}:{1}", timeToFill.Minutes, timeToFill.Seconds);
remainingEnergy.text = stamina + "/" + maxStamina;
}
}