Hey Everyone, so I am brand new to Unity and was decided to just go trial by fire and make my own idle game. I was wanting to have a counter at the top that added a day every two seconds. I was messing around with a bunch of methods, but was wondering if anyone could help me. This is what I got so far. Also for a later time, does anyone know a way I could pause the timer and game after that? Im sure this is all pretty bad, but I am just hoping to pick all of this up
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class LevelScript : MonoBehaviour
{
public Text dayText;
public float days;
private int daysInt;
void Start()
{
}
private void Update()
{
days = Time.time / 2;
int daysInt = (int)days;
dayText.text = "Days: " + days.ToString("0");
}
}
int days;
void Update()
{
days = (int)Time.time / 2;
Debug.Log(days);
}
or
void Start()
{
StartCoroutine(EveryTwoSecond());
}
int days;
IEnumerator EveryTwoSecond()
{
while(true)
{
yield return new WaitForSeconds(2);
days++;
Debug.Log(days);
}
}
Hey there and welcome.
in general when facing something like this i’d strongly suggest you read the documentation on things you try to use.
For example Time.time;
will give you the time since game startup in seconds. You probably rather want to have that since level load since there might be a main menu when you start up the game.
Then in general what you du seems ok to me except that you define a local variable daysInt
when you already have a member variable with that name. There are some other ways to do stuff like this.
My favorite would probably to use a coroutine since this removes clutter from the Update function:
public IEnumerator dayTimer()
{
while(true)
{
yield return new WaitForSeconds(2f);
intDays++;
dayText.text = "Days: " + intDays;
}
}
As for your question on “how to pause” the game: That basically depends on you and how you want to design this. It basically also depends on what your game does. Most games using physics set the timescale to 0 i think. This should in theory then also automatically pause the WaitForSEconds
yield statement of your day counter.
Thank you guys so much, I got the timer working. Its crazy starting a hobby so expansive, so thank you