如何从System.Timers.Timer处理程序调用Random.Range?

时间:2017-01-16 16:25:23

标签: c# unity3d random thread-safety

所以Random.Range只能从主线程中调用。

对于以下我需要System.Timers.Timer处理程序中的随机变量的解决方案是什么?

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);
    }
}

1 个答案:

答案 0 :(得分:1)

this问题中获取UnityThread课程。然后,您可以在Random.Range函数中使用Unity的UnityThread.executeInUpdate

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);
    });
}