Unity c# set timer on background even if game is not active - c#

I have a game where I have time to give energy. My timer works fine when game is active but when game is inactive the time pauses and after I start game again the timer starts from wher it was left.
I want keep timer going even if the game is inactive and add energy.
using System;
using UnityEngine;
using UnityEngine.UI;
public class EnergyAdder : MonoBehaviour
{
// Start is called before the first frame update
public float waitTime = 600;
Timer timer;
public GameRoot gameRoot;
void Awake()
{
//timer = new Timer(waitTime);
float remainingTime = PlayerPrefs.GetFloat("TimeOnExit");
timer = new Timer(remainingTime);
}
// Update is called once per frame
void Update()
{
if (gameRoot.energyCap >= 5)
{
GetComponent<Text>().text = "Full";
timer.refresh();
}
else
{
timer.countDown();
if (timer.isFinished())
{
timer = new Timer(waitTime);
timer.refresh();
gameRoot.AddEnergy(1);
}
UpdateClock();
}
}
void UpdateClock()
{
int seconds = ((int)timer.timeLeft) % 60;
int minutes = (int)(timer.timeLeft / 60);
GetComponent<Text>().text = minutes.ToString() + ":" + seconds.ToString("00");
}
void OnApplicationQuit()
{
PlayerPrefs.SetFloat("TimeOnExit", timer.timeLeft);
}
}
Please help I'm new to unity and c#.

What you are doing is saving time value when you left, and load that value when you start the game again.
Maybe you should (when start the game) compare that loaded time with the current time, the difference will be the time elapsed.

Related

Unity static value

I have a countdown timer, and when that timer end it goes to a game over scene that i can press to exit. The problem is when i try to start a new game it goes automatically to the game over scene because the time already passed.
private static float timer = 30f;
void Update ()
{
timer -= Time.deltaTime;
timerSeconds.text = timer.ToString("f0");
if (timer <= 0)
{
Application.LoadLevel (LevelToLoad);
}
}
How do reset it properly?
You never reset the timer and since it is static it keeps it's value after scene changes.
Depending a bit on your exact needs
Either simply don't make it static
reset it on game over
if (timer <= 0)
{
timer = 30f;
Application.LoadLevel (LevelToLoad);
}
reset it at the start of a scene
private void Start()
{
timer = 30;
}

Application Unity UI

Two days ago I started creating an application for a friend using a tutorial on youtube. Basically I'm trying to create an app with a timer. Simple background, simple script. This is the code I'm using:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Timer : MonoBehaviour
{
public Text TimerText;
public float countdownTime = 181;
// Update is called once per frame
void Update()
{
countdownTime -= Time.deltaTime;
int minutes = Mathf.FloorToInt(countdownTime / 60F);
int seconds = Mathf.FloorToInt(countdownTime - minutes * 60);
string niceTime = string.Format("{0:0}:{1:00}", minutes, seconds);
TimerText.text = niceTime;
}
}
The problem is that I can't figure it out how to make a button that when its first pressed it should start the timer and when its pressed second it should reset it. I've just started using c#.
https://prnt.sc/rcknb8 (this is what I got till now)
Set the variable "countdownTime" back to its default number when the button is pressed.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Timer : MonoBehaviour {
public Text TimerText;
public float countdownTime = 0;
public float defaultCountdownTime = 181;
// Update is called once per frame
void Update()
{
if(countdownTime > 0)
{
countdownTime -= Time.deltaTime;
int minutes = Mathf.FloorToInt(countdownTime / 60F);
int seconds = Mathf.FloorToInt(countdownTime - minutes * 60);
string niceTime = string.Format("{0:0}:{1:00}", minutes, seconds);
TimerText.text = niceTime;
}
}
void ButtonPress()
{
countdownTime = defaultCountdownTime;
}
}
You have to define the parameters initialized before and then make a simple calculation using modulo
"""For instances guys, i create a simple SkaterBoard game using simple gravity physics with Android Studio, I would really appreciate if you could left a review on it."""
(Android Link) Skater Soldier Game: https://play.google.com/store/apps/details?id=com.fight.exempleclass

Cooldown timer doubles in speed every time my startup countdown is executed

When the player dies, one heart is removed from the health bar. A cool down timer starts that will refill the heart after 5 minutes. If the player should die again, the second heart will be removed but the timer will first finish its current cool down before restarting.
When the player dies the second time, the scene reloads and a countdown is shown to give the player time to get ready for the next try.
The problem is as soon as the countdown is finished and the timescale is set to 1, the cool down timer speed increases. If he dies again the timer speed increases again, till the first cool down timer completes and then resets and start the next cool down, then the speed is back to normal or if I exit the game and re-enter the timer is back to normal.
When the scene loads the timescale is 0. The countdown animation runs using a Mycoroutine script. After the animation is finished the timescale is set back to 1.
The cool down timer takes into account the time that a player is offline using a TimerMaster script and works 100%. Tested it on android and if the game moves to the background the timer works fine, using Time.unscaledDeltaTime instead of Time.DeltaTime.
The only problem I can't figure out is the speed increase every time the level restarts.
//this is used to call the countdown
public bool setCoundown = false;
void Start()
{
countDown.SetActive(true); //when active it sets setCountdown to true
Time.timeScale = 0;
}
void Update()
{
if (setCoundown)
{
StartCoroutine(CountDown()); //set the timer to wait till the countdown is done
}
}
IEnumerator CountDown()
{
while (setCoundown == true)
{
yield return StartCoroutine(Mycoroutine.WaitforRealSeconds(0.5f));
setCoundown = false;
Time.timeScale = 1;
RunGame();
}
}
//This script is called by CountDown()
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class Mycoroutine
{
public static IEnumerator WaitforRealSeconds(float time)
{
float start = Time.realtimeSinceStartup;
while(Time.realtimeSinceStartup < (start + time))
{
yield return null;
}
}
}
//This is the cool down timer
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class TimerText : MonoBehaviour
public static TimerText instance;
[SerializeField]
private Text timeText;
private int health;
private float timer, minutes, seconds;
void Start()
{
//get saved time that was needed to fill all health
timer = GameController.instance.GetTimerTime();
//deduct the offline time from the needed time
timer = timer - TimerMaster.instance.CheckDate();
//call the function to calculate offline time and set lives and timer value accordingly if the health is full then the timer value will be 300
DateTimer();
}
void Update()
{
health = GameController.instance.GetHealth();
if (health < 3 && timeText.text == "0:00")
{
StartCoundownTimer();
}
}
void StartCoundownTimer()
{
if (timeText != null)
{
timeText.text = "0:00";
InvokeRepeating("UpdateTimer", 0.0f, 0.01667f);
}
}
void UpdateTimer()
{
if (timeText != null)
{
timer -= Math.Max(Time.unscaledDeltaTime, 0);
timeText.text = string.Format("{0}:{1:00}", (int)(timer / 60), (int)(timer % 60));
if (timeText.text == "0:00")
{
CancelInvoke();
health = GameController.instance.GetHealth() + 1;
GameController.instance.SetHealth(health);
timer = 300;
}
}
}

How to increase my score gradually with a timer?

I am currently creating a hidden object game and I have been stuck on how to add a timer and countdown to my game. I have currently a score which generates after all of the objects have been clicked however I would love if the score went up gradually once the user clicked on each one. here is my code below so far.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class trackingclicks : MonoBehaviour {
//static variable added to count users clicks
public static int totalclicks=0;
//"mouseclick" keycode variable to look for mouse click
public KeyCode mouseclick;
public Transform scoreObj;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//checks the change in time, aka how much time has passed- bonus time starts at 90
clickcontrol.timeBonus -= Time.deltaTime;
if (clickcontrol.remainItems == 0)
{
clickcontrol.totalScore += (70 + (Mathf.RoundToInt(clickcontrol.timeBonus)));
scoreObj.GetComponent<TextMesh>().text = "Score : " + clickcontrol.totalScore;
clickcontrol.remainItems = -1;
}
//Check for mouse click
if (Input.GetKeyDown (mouseclick))
{
totalclicks += 1;
}
if (totalclicks >= 5)
{
Debug.Log ("FAIL!!!");
totalclicks = 0;
}
}
}
You can use coroutines for timers (coroutines execute code after a certain amount of time). If you want your score to increment gradually once the player clicks on an object (I think that's what you're asking), then something like this should work:
public int score;
IEnumerator IncrementScore(int amount, int interval) { //amount is the amount of score to add over the time, interval is the time IN SECONDS between adds
for (int i = 0; i < amount; i++) {
yield return new WaitForSeconds(interval);
score++;
}
}
I wasn't sure where the score variable was so I made a new one; you can set it to your own, wherever it is. If you need more help, feel free to ask.

stopping delta time c#

I'm trying to display 3 times at once for a turn based game.
The first time is total time being counted down.
The other two timers shows countdown time for each player.
I also have a boolean value being checked from another class to see which turn it is(myplayerturn)
Right now I can show total time and player time all counting down effectively, but when one player time is running i want to pause the other player timer. So far my code is as follows
public class countDown : MonoBehaviour {
public Text timerText;
public Text PlayerTime;
public Text OpponentTime;
public float myTimer = 3600;
// Use this for initialization
void Start () {
timerText = GetComponent<Text>();
PlayerTime = GetComponent<Text>();
OpponentTime = GetComponent<Text>();
}
// Update is called once per frame
void Update () {
if (GetComponent<differentclass>().myplayerturn)
{
//I'm gueussing this is where i need to pause OpponentTime;
// and start PlayerTime
}
else{
// pause PlayerTime
}
int minutes = Mathf.FloorToInt(myTimer / 60F);
int seconds = Mathf.FloorToInt(myTimer - minutes * 60);
string rTime = string.Format("{0:00}:{1:00}", minutes, seconds);
myTimer -= Time.deltaTime;
timerText.text = rTime;
PlayerTime.text = rTime;
OpponentTime.text = rTime;
}
}
I would store minutes and seconds in a small class and give every player a class and when its paused just dont increment the time.
That would look like this:
public class PlayerTime {
public int seconds = 0;
public int minutes = 0;
public float myTimer = 3600;
}
Then inside of the update I would just use the persons class variable.

Categories