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
Related
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Scenes_Test : MonoBehaviour
{
public float duration;
public Image image;
private void Start()
{
StartCoroutine(ImageFade(image, 1, duration));
SceneManager.LoadScene(1, LoadSceneMode.Single);
}
void Update()
{
}
public IEnumerator ImageFade(
Image sr,
float endValue,
float duration)
{
float elapsedTime = 0;
float startValue = sr.color.a;
while (elapsedTime < duration)
{
elapsedTime += Time.deltaTime;
float newAlpha = Mathf.Lerp(startValue, endValue, elapsedTime / duration);
sr.color = new Color(sr.color.r, sr.color.g, sr.color.b, newAlpha);
yield return null;
}
}
}
The logic is to fade to 1 make it black screen when loading the new scene.
and then when the new scene has loaded to fade in back to 0.
the problem is that in this way it's just loading the new scene too fast and never fade.
this script is attached to object in the current loaded scene.
in the Editor > File > Build Settings... i added both scenes already.
In the New Scene i have just a Main Camera and Directional Light
Use DontDestroyOnLoad in your class to make sure it also exists after a scene change.
It would also be better to not use a fixed duration but to check when the scene is actually done loading so it still works for more complex scenes.
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.
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;
}
}
}
I am trying to use this script to set a timer for someone looting a player however i can't get it to reset after i call it a second time but it stores the original value of time left where as i want it to start fresh each time.
i am calling it from another script which enables and disables it on the OnTriggerEnter and OnTriggerExit methods
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Changetext : MonoBehaviour {
public float timeLeft = 5;
public Text countdownText;
public float cash = 0;
// Use this for initialization
void start()
{
timeLeft = 5;
}
void Update()
{
timeLeft -= Time.deltaTime;
countdownText.text = ("Time Left = " + timeLeft);
if (timeLeft <= 0)
{
countdownText.text = "You got the cash";
cash = 1;
}
}
}
Start() only gets called once in the gameobjects lifetime - so it won't toggle everytime you enable/disable.
You can instead use OnEnable() to reset the timer to 5;
void OnEnable()
{
timeLeft = 5;
}
(as an FYI, Start() needs a capital 'S')
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.