2017-01-16 3 views
1

したがって、Random.Rangeはメインスレッドからのみ呼び出すことができます。System.Timers.Timerハンドラから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

クラスをthisから取得します。 UnityThread.executeInUpdate機能でUnityのRandom.Rangeを使用することができます。

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); 
    }); 
} 
関連する問題