neuecc / UniRx

Reactive Extensions for Unity
MIT License
7.01k stars 895 forks source link

Bug: Observable.Delay with Scheduler.MainThread ignores Time.timeScale > 1f, and is inaccurate for Time.timeScale < 1f #484

Open RobinB-Gbanga opened 3 years ago

RobinB-Gbanga commented 3 years ago

Environment:

I've ran the following test, once with Time.timeScale = 0.5f and once with Time.timeScale = 2f:

Subject<Unit> test = new Subject<Unit>();

Time.timeScale = 2f;

Stopwatch sw1 = new Stopwatch();
Stopwatch sw2 = new Stopwatch();

sw1.Start();
sw2.Start();

TimeSpan delay = TimeSpan.FromSeconds(5);

test.Delay(delay, Scheduler.MainThread).Subscribe(_ =>
{
  sw1.Stop();
  Debug.Log($"MainThread Elapsed: {sw1.Elapsed}");
});

test.Delay(delay, Scheduler.MainThreadIgnoreTimeScale).Subscribe(_ =>
{
  sw2.Stop();
  Debug.Log($"MainThreadIgnoreTimeScale Elapsed: {sw2.Elapsed}");
});

sw1.Start();
sw2.Start();

test.OnNext(Unit.Default);

Results:

Time.timeScale = 0.5f:

MainThreadIgnoreTimeScale Elapsed: 00:00:05.0037869 MainThread Elapsed: 00:00:12.1778941

Observation: Expected MainThread to clock in at roughly 00:00:10.0, but took over 2 seconds longer than expected.

Time.timeScale = 2f:

MainThread Elapsed: 00:00:05.0028989 MainThreadIgnoreTimeScale Elapsed: 00:00:05.0076844

Observation: Expected MainThread to clock in at roughly 00:00:02.5, but took the same time as MainThreadIgnoreTimeScale.

I've tested different time measurement methods (System.Diagnostics.Stopwatch, UnityEngine.Time.unscaledTime, (DateTime.Now - StartDateTime)) and always got the same results.

I've also tested running this immediately on app start, or some seconds after (to give enough time for any warm-up / frame-skips that may occur), and with or without waiting a bit after setting Time.timeScale. Always the same results.

I also ran equivalent tests on Observable.Timer(dueTime, period, scheduler), and everything works correctly there. So the bug is limited to Observable.Delay, it seems.

Please do let me know if I can provide any further information!