Game Loop
Game Loop
Section titled “Game Loop”One-line pattern summary
Section titled “One-line pattern summary”The core execution pattern of games that maintains a stable input-update-render loop.
Typical Unity use cases
Section titled “Typical Unity use cases”- When implementing a fixed-step simulation.
- When input timing and render timing should be separated.
Parts (roles)
Section titled “Parts (roles)”- Input Step
- Simulate Step
- Render Step
Unity example (C#)
Section titled “Unity example (C#)”The code below is a simplified Unity example based on the scenario described above.
using UnityEngine;
public sealed class FixedStepLoop : MonoBehaviour{ private const float SimulationStep = 1f / 60f; private float accumulatedDeltaTime;
private void Update() { accumulatedDeltaTime += Time.deltaTime;
while (accumulatedDeltaTime >= SimulationStep) { Simulate(SimulationStep); accumulatedDeltaTime -= SimulationStep; }
float interpolationAlpha = accumulatedDeltaTime / SimulationStep; Render(interpolationAlpha); }
private void Simulate(float deltaTime) { } private void Render(float interpolationAlpha) { }}Advantages
Section titled “Advantages”- A fixed update order improves simulation reproducibility and makes debugging safer.
- Separating fixed-step updates from interpolation helps balance physics accuracy and visual smoothness.
Things to watch out for
Section titled “Things to watch out for”- On heavy frames, the
whileloop can grow too long and lead to a spiral of death. - If responsibilities between
UpdateandFixedUpdateare mixed, input latency and physics errors can increase.
Interaction diagram
Section titled “Interaction diagram”This is the main loop that repeats input, simulation, and render on a frame basis.