Skip to content

Instantly share code, notes, and snippets.

@Rovsau
Last active October 10, 2023 04:06
Show Gist options
  • Save Rovsau/d4858c66c9259f3eb6df5238777c1c95 to your computer and use it in GitHub Desktop.
Save Rovsau/d4858c66c9259f3eb6df5238777c1c95 to your computer and use it in GitHub Desktop.
PostFixedUpdate - Call after FixedUpdate and OnPhysicsXXX

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);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment