有没有办法获得Observable.Timer的“进展”

时间:2017-11-20 22:04:11

标签: c# unity3d system.reactive

目前我按预期工作

Observable.Timer(TimeSpan.FromSeconds(5))
            .Subscribe(x => MessageBroker.Default.Publish(new Messages.Serve()));

我想基于此Observables的剩余时间显示倒计时,但无法找到访问计时器当前值的方法。

有没有办法在不包装整个事物并分别跟踪进度的情况下执行此操作?

1 个答案:

答案 0 :(得分:2)

在Unity中制作计时器时,除非有充分的理由不这样做,否则请先尝试使用Unity API。如果进行倒计时器,则每帧递减Time.detalTime的定时器变量。这可以在Update或协程函数中完成。如果您希望能够使用多个此实例,请将其放在自己的类中。

public struct CountDownTimer
{
    private static int sTimerID = 0;
    private MonoBehaviour monoBehaviour;

    public float timer { get { return localTimer; } }
    private float localTimer;

    public int timerID { get { return localID; } }
    private int localID;

    public CountDownTimer(MonoBehaviour monoBehaviour)
    {
        this.monoBehaviour = monoBehaviour;
        localTimer = 0;

        //Assign timer ID
        sTimerID++;
        localID = sTimerID;
    }

    public void Start(int interval, Action<float, int> tickCallBack, Action<int> finshedCallBack)
    {
        localTimer = interval;
        monoBehaviour.StartCoroutine(beginCountDown(tickCallBack, finshedCallBack));
    }

    private IEnumerator beginCountDown(Action<float, int> tickCallBack, Action<int> finshedCallBack)
    {
        while (localTimer > 0)
        {
            localTimer -= Time.deltaTime;
            //Notify tickCallBack in each clock tick
            tickCallBack(localTimer, localID);
            yield return null;
        }

        //Notify finshedCallBack after timer is done
        finshedCallBack(localID);
    }
}

<强>用法

//Create new Timer
CountDownTimer timer = new CountDownTimer(this);

//What to do each second time tick in the timer
Action<float, int> tickCallBack = (currentTime, timerID) =>
{
    Debug.Log("Time Left: " + currentTime + "  ID: " + timerID);
};


//What to do when timer changes
Action<int> finshedCallBack = (timeriD) =>
{
    Debug.Log("Count Down Timer Done! ID: " + timeriD);
};

//Start Countdown Timer from 5
timer.Start(5, tickCallBack, finshedCallBack);

如果您愿意,可以随时使用CountDownTimer.timer变量访问计时器进度。虽然,我更喜欢使用上面的Action,并在进度发生变化时收到通知。