2

So Random.Range can only be called from the Main thread.

What would be the solution then for the following where I need a random variable within a System.Timers.Timer handler?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FooCounter : MonoBehaviour 
{
    private  int _randomFoo;
    private System.Timers.Timer _t = new System.Timers.Timer();

    // Use this for initialization
    void Start()
    {
        _t.Interval = 1000;
        _t.Elapsed += TimerUpdate;
        _t.Start();
    }
    public void TimerUpdate(object sender, System.Timers.ElapsedEventArgs e)
    {
        _randomFoo = Random.Range(0, 20);
    }
}
Programmer
  • 121,791
  • 22
  • 236
  • 328
Bachalo
  • 6,965
  • 27
  • 95
  • 189

1 Answers1

1

Get the UnityThread class from this question. You can then use Unity's Random.Range in the UnityThread.executeInUpdate function.

private  int _randomFoo;
private System.Timers.Timer _t = new System.Timers.Timer();

void Awake()
{
    UnityThread.initUnityThread();
}

// Use this for initialization
void Start()
{
    _t.Interval = 1000;
    _t.Elapsed += TimerUpdate;
    _t.Start();
}


public void TimerUpdate(object sender, System.Timers.ElapsedEventArgs e)
{
    UnityThread.executeInUpdate(() =>
    {
        _randomFoo = Random.Range(0, 20);
    });
}
Community
  • 1
  • 1
Programmer
  • 121,791
  • 22
  • 236
  • 328