This is my concept for the timer, I just wanted to get some opinions on it before I implement it into Unity:
int Minute = 60;
for (int Second = 1; Second < Minute; Second = Minute / 60 * Time.deltaTime);
Would this go up once a second or because im using Time.deltaTime would it still go up frame by frame?
CodePudding user response:
Dude, don't use this. This would cause hundreds of problems and poor performance.
You have a few options like:
//Import Library.
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
//...
//Freeze the code for 1 Sec.
Thread.Sleep(1000);
//OR create a Timer (Better Solution)
private static void SetTimer()
{
// Create a timer with a two second interval.
aTimer = new System.Timers.Timer(2000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed = OnTimedEvent;
aTimer.Enabled = true;
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
//Code run after 2 Sec.
//aTimer.Enabled = false;
//To Stop the Timer.
}
But... If you're using Unity, I can't help you, this solution works for Net Framework and Core.
If you use Unity you will have to search deeper or even "try" to use this code.
CodePudding user response:
You can make the function that needs a timer a coroutine like this:
IEnumerator YourFunction(int waitTime)
{
yield return new WaitForSeconds(waitTime); //Also accepts float values
//do something
}
Keep in mind that you cannot call coroutines like normal functions, so you will need to use:
StartCoroutine(YourFunction(3)); //For example, this will wait 3 seconds.
Also IEnumerator is within the System.Collections library.
CodePudding user response:
I'd reccomend using a built in mechanism for a timer.
Where there is nothing happening inside of your for loop, it's going to just add the current second over and over again, causing the loop to act like it almost didn't exist. Here's what I recommend if you insist using your own timer instead of something pre built.
for(int seconds = 0; seconds < 60; seconds )
{
DateTime startTime = DateTime.Now;
//Whatever code you want to be executed
if(DateTime.Now.Second == startTime.Second)
{
//Loop will add one, so if a second hasn't passed, remove one
seconds--;
}
else if(DateTime.Now.Second > startTime.Second 1)
{
//If more than one second has passed, add the time that will
//be missed by just adding one
seconds = DateTime.Now.Second - (startTime.Second 1);
}
}