【问题标题】:How to call Random.Range from System.Timers.Timer handler?如何从 System.Timers.Timer 处理程序调用 Random.Range?
【发布时间】:2017-05-31 13:13:36
【问题描述】:

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

【问题讨论】:

    标签: c# unity3d random thread-safety


    【解决方案1】:

    this 问题中获取UnityThread 类。然后,您可以在 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);
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多