In this lesson, you will learn how to prevent frame rate spikes in dense crowds by time-slicing your AI's heavy decision-making calculations across multiple frames.
When you have dozens of NPCs running complex GOAP planners or Utility selectors simultaneously, calculating every agent's logic in a single Update() call will cause a "hitch." The CPU becomes overwhelmed, leading to dropped frames. Instead of forcing every agent to make a decision every single frame, we distribute the workload using a time-sliced execution pattern.
The Round-Robin Time-Slicing Pattern
The core idea is to create a "Task Queue" or a rotation where only a subset of your agents runs their logic per frame. You can achieve this by maintaining a list of your AI controllers and iterating through them over several frames, rather than all at once.
Consider this simplified implementation:
private int _nextAgentIndex = 0;
private List<AIAgent> _agents; // List of all NPCs
public int batchSize = 5; // Agents processed per frame
void Update()
{
// Process only a small batch of agents per frame
for (int i = 0; i < batchSize; i++)
{
if (_nextAgentIndex >= _agents.Count) _nextAgentIndex = 0;
_agents[_nextAgentIndex].UpdateDecisionLogic();
_nextAgentIndex++;
}
}
Why This Works
By setting a batchSize, you define exactly how much "AI budget" you spend per frame. If you have 100 agents and a batch size of 5, each agent only performs its decision-making logic once every 20 frames. For most games, this update frequency is more than sufficient, as player perception of "instant" AI responsiveness is often less important than maintaining a smooth 60 FPS.
If an agent needs an urgent reaction—like reacting to an immediate attack—you can bypass the queue for that specific instance, but keep the standard decision-making loops throttled. This approach keeps the CPU load flat and predictable, even as your population size grows.
Key Takeaway: By spreading your AI logic across multiple frames using a controlled batching system, you decouple simulation density from frame rate stability.