- Home /
How to use a random integer from range inside a timer?
Hi guys, web dev here trying Unity for the first time.
I've created a System.Timer from Start() with an interval of one second, which I've confirmed is executing the callback using a log, here's the setup:
timer = new Timer(1000);
timer.Elapsed += Tick;
timer.Start();
Here's the callback:
void Tick(object sender, ElapsedEventArgs e)
{
Debug.Log("timer tick");
int rnd = Random.Range(1, 359);
Debug.Log(rnd);
}
The output I'm getting shows the timer tick message, but nothing else. No code I place after the range method is working. The range method works fine in constructor methods for example, but not within this timer callback, am I missing something? Thanks!
I am also looking for the same to produce random integers in a given range $$anonymous$$yCFAVisit.
Answer by TomArano_Dimenco · Jun 15, 2020 at 10:33 AM
Dont exactly know why this is happening.. however it can be fixed using the "System.Random" instead of "UnityEngine.Random".
Debug.Log("timer tick");
System.Random rand = new System.Random();
int rnd = rand.Next(1, 359);
Debug.Log(rnd);
Also, seems timers wil not stop executing when stopping unity playback (this might cause problems later).
As you are new to Unity, unity has its own 'timer' system we usually use coroutines to do stuff like this
void Start()
{
StartCoroutine(triggerRandomNumber());
}
IEnumerator triggerRandomNumber()
{
while (true) //this is allowed in coroutines when yielding with delay (waitforseconds)
{
yield return new WaitForSeconds(1);
Debug.Log("timer tick");
int rnd = UnityEngine.Random.Range(1, 359);
Debug.Log(rnd);
}
}
Thanks $$anonymous$$! In the end, I simply used Time.time in the update function to roll-my-own timers. Good to know about Coroutines. I use Goland in my work day-to-day so you'd think I'd have considered that. :),Hi $$anonymous$$!
Thanks for your help. I hadn't considered a Coroutine (funny, since my work is mostly in Golang!) but in the end, I simply used Time.time in the update function to create my own ti$$anonymous$$g methods. This seems to work, good to know I wasn't making an obvious mistake, though, seems like it could be a bug.
Thanks!
not sure if its bugged or intended behaviour. might be intended since timer keeps running out of play mode u cant use unity functions in there.
https://docs.unity3d.com/ScriptReference/Time-deltaTime.html $$anonymous$$ight be worth checking out aswell (since u are new with unity).. works great for making time based movement/functions.