Course contentsShow
← Unity Game Development
Lesson 135 of 8282. Scripting and LifecycleFree lesson

Implementing Time-Sliced Processing for Performance

Distribute heavy calculations across multiple frames to maintain high frame rates by processing data in small chunks within a coroutine.

In this lesson, you will learn how to prevent "frame spikes" by spreading heavy computational tasks across multiple frames using time-sliced processing.

The Problem: The "All-at-Once" Bottleneck

When you perform a heavy operation—like calculating a complex path for an AI army or spawning a thousand objects—in a single frame, your game execution pauses until the work is finished. This creates a sudden drop in frame rate, often called a "hitch" or "stutter." If a calculation takes 50 milliseconds but your game needs to render at 60 FPS (roughly 16 milliseconds per frame), the player will clearly feel the game freeze.

The Solution: Time-Slicing

Time-slicing breaks a massive task into tiny, manageable chunks. Instead of finishing the entire job in one frame, you process a small portion, yield control back to Unity, and resume the work in the next frame. By the time the next frame arrives, Unity has already handled the rendering, keeping the experience smooth.

Implementation with Coroutines

You can achieve this using a Coroutine. We define a loop that processes a subset of data and yields using yield return null, which tells Unity to pause the function and resume it on the following frame.

IEnumerator ProcessHeavyData(List<int> largeDataSet)
{
    int itemsPerFrame = 10;
    
    for (int i = 0; i < largeDataSet.Count; i++)
    {
        // Perform the heavy work on one item
        DoWork(largeDataSet[i]);

        // Every 10 items, pause to let the game render the frame
        if (i % itemsPerFrame == 0)
        {
            yield return null; 
        }
    }
}

By checking the i % itemsPerFrame condition, we ensure that we aren't hogging the CPU for too long. If you find the game is still stuttering, simply lower the itemsPerFrame value. If the task is taking too long to finish, you can increase it. This balancing act allows you to maintain a steady frame rate while still processing vast amounts of data in the background.

Key Takeaway: Time-slicing keeps your game responsive by breaking large operations into smaller chunks that pause and resume over several frames, ensuring no single frame takes too long to complete.