0
0
Unityframework~5 mins

Performance profiling in Unity

Choose your learning style9 modes available
Introduction

Performance profiling helps you find parts of your Unity game that run slowly. It shows where your game uses too much time or memory so you can fix it.

When your game feels slow or laggy during play.
When you want to check if a new feature affects game speed.
Before releasing your game to make sure it runs smoothly.
When you want to reduce battery or CPU usage on devices.
To find and fix memory leaks that cause crashes.
Syntax
Unity
Open the Unity Editor > Window > Analysis > Profiler
Use the Profiler window to record and view performance data.
You can also add custom markers in code:
using UnityEngine.Profiling;

Profiler.BeginSample("MySample");
// code to measure
Profiler.EndSample();
The Profiler window shows CPU, GPU, memory, rendering, and more.
Use Profiler.BeginSample and EndSample to measure specific code blocks.
Examples
This measures how long the Update loop takes each frame.
Unity
Profiler.BeginSample("UpdateLoop");
// code inside Update
Profiler.EndSample();
This measures the time taken to load assets.
Unity
Profiler.BeginSample("LoadAssets");
LoadAssets();
Profiler.EndSample();
This shows how to start profiling without code.
Unity
// Open Profiler window from Unity Editor menu
// Click Record to start profiling
// Play your game to see live data
Sample Program

This script measures how long the HeavyCalculation method takes every frame. You can see this in the Profiler window under the "HeavyCalculation" sample.

Unity
using UnityEngine;
using UnityEngine.Profiling;

public class PerformanceTest : MonoBehaviour
{
    void Update()
    {
        Profiler.BeginSample("HeavyCalculation");
        HeavyCalculation();
        Profiler.EndSample();
    }

    void HeavyCalculation()
    {
        float sum = 0f;
        for (int i = 0; i < 100000; i++)
        {
            sum += Mathf.Sqrt(i);
        }
    }
}
OutputSuccess
Important Notes

Profiling can slow down your game while running, so use it mainly in the Editor or development builds.

Look for spikes or long bars in the Profiler timeline to find slow parts.

Combine profiling with testing on real devices for best results.

Summary

Performance profiling helps find slow or costly parts of your game.

Use the Unity Profiler window or add custom samples in code.

Fixing issues found by profiling makes your game smoother and faster.