UnityAsync icon indicating copy to clipboard operation
UnityAsync copied to clipboard

WaitForFixedUpdate incorrect finishFrame

Open cfoulston opened this issue 4 years ago • 1 comments

When calling await Await.FixedUpdates(1) inside a while loop. The iterator will not continue until the fixedCount reaches updateCount.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityAsync;

public class TestAsync : MonoBehaviour {

	#region Private Methods

	public void DoRoutineAtSomeTime() { 

		DoRoutine();
	}

	private async void DoRoutine() {

		while (isActiveAndEnabled) {

			Debug.Log("Before " + Time.inFixedTimeStep);

			await Await.FixedUpdates(1).ConfigureAwait(this);

			//This will not occur until a long time later, depending on when "DoRoutine" was called

			Debug.Log("After " + Time.inFixedTimeStep);
		}

		Debug.Log("Finished");
	}

	#endregion
}

This is because in the constructor of "WaitForFrames" the finishFrame is set to CurrentFrameCount + count

#if UNITY_EDITOR
using UnityEngine;
#endif

namespace UnityAsync
{
	public struct WaitForFrames : IAwaitInstruction
	{
		readonly int finishFrame;

		bool IAwaitInstruction.IsCompleted() => finishFrame <= AsyncManager.CurrentFrameCount;
		
		/// <summary>
		/// Waits for the specified number of frames to pass before continuing.
		/// </summary>
		public WaitForFrames(int count)
		{
			#if UNITY_EDITOR
			if(count <= 0)
			{
				count = 1;
				Debug.LogError($"{nameof(count)} should be greater than 0. This check will only appear in edit mode.");
			}
			#endif

			finishFrame = AsyncManager.CurrentFrameCount + count;
		}
	}
}

So if you call Await.FixedUpdates(1) when not inside a FixedUpdate callback, the finishFrame is set to the AsyncManager.updateCount instead of AsyncManager.fixedCount

cfoulston avatar Jan 20 '21 22:01 cfoulston

The solution so far is to always await new UnityEngine.WaitForFixedUpdate() before calling await Await.FixedUpdates(1)

cfoulston avatar Jan 20 '21 22:01 cfoulston