FixedUpdate runs before OnTrigger/Collision/MouseXXX.
PostFixedUpdate runs after all of them.
Which eliminates a 1-frame desync in many solutions.
Drawback: Coroutines generate garbage.
using System.Collections;
using UnityEngine;
/// <summary>
/// FixedUpdate runs before OnTrigger/Collider/MouseXXX.
/// PostFixedUpdate runs after all of these calls (on the same instance), on the same frame.
/// </summary>
public class PostFixedUpdate_Example : MonoBehaviour
{
private int _frame;
private WaitForFixedUpdate _waitForFixedUpdate;
private Coroutine _postFixedUpdate;
private void Awake()
{
_waitForFixedUpdate = new WaitForFixedUpdate();
}
private void OnEnable()
{
_postFixedUpdate = StartCoroutine(PostFixedUpdate());
}
private void FixedUpdate()
{
Debug.Log(_frame + " FixedUpdate " + this.name);
}
private void OnTriggerStay(Collider other)
{
Debug.Log(_frame + " OnTriggerStay " + this.name);
}
private IEnumerator PostFixedUpdate()
{
while (true)
{
yield return _waitForFixedUpdate;
Debug.Log(_frame + " After FixedUpdate " + this.name);
}
}
private void Update()
{
_frame++;
}
private void OnDisable()
{
StopCoroutine(_postFixedUpdate);
}
}