---
title: 可视性能分析器数器
product: Unity Editor
version: '6000.0'
latest_version: '7000.0'
status: This page documents version 6000.0. The latest version is 7000.0.
canonical: https://docs.unity.com/zh-cn/engine/6000.0/manual/analysis/profiler/customizing/adding-information-code/creating-custom-counters
latest_url: https://docs.unity.com/zh-cn/engine/7000.0/manual/analysis/profiler/customizing/adding-information-code/creating-custom-counters.md
last_updated: 2026-10-30
generated_at: 2026-11-16T16:22:53.142Z
locale: zh-cn
---

# 可视性能分析器数器

> 将性Add Profiler到自定义性能性能分析器模块。

[向代码添加性能](/engine/6000.0/manual/analysis/profiler/customizing/adding-information-code/add-counters-code.md)分析器计数器后，即可在性能分析器窗口或应用程序的版本中可视化它们。

## 在 性能分析器 窗口中可视化自定义计数器##visualizing-custom-counters-in-the-profiler-window

要查看`ProfilerCounter`或`ProfilerCounterValue`在性能分析器窗口中生成的数据，可以使用[自定义性能分析器模块](/engine/6000.0/manual/analysis/profiler/customizing.md)。这可能有助于直观识别与OtherSystemMetrics的关系并快速识别性能问题。

### 向代码添加 Metrics##adding-metrics-to-your-code

以下示例假设 GameManager 类处理高关卡逻辑并了解敌人。要更新计数器的值，请使用 `Update` 或 `LateUpdate` 方法（取决于何时对生成或销毁敌人执行逻辑 ON），使用 `Sample` 方法将敌人的数量值推送到性能分析器：

```lang-cs
using UnityEngine;
using Unity.Profiling;

类 GameManager：MonoBehaviour
{
    Enemy[] m_Enemies;

    void Update()
    {
        GameStats.EnemyCount.Sample(m_Enemies.Length);
    }
}
```

要将子弹数量通道给性能性能分析器，此示例假设有一个 shell 脚本可以管理子弹Lifecycle。然后以`Awake`为单位增加`GameStats.BulletCount`值并减小该值，`OnDestroy`便提供有关游戏中当前子弹流的准确信息。

```lang-cs
using UnityEngine;
using Unity.Profiling;

public class Shell :MonoBehaviour
{
    void Awake()
    {
        GameStats.BulletCount.Value += 1;
    }
    void OnDestroy()
    {
        GameStats.BulletCount.Value -= 1;
    }
}
```

> **Note:**
>
> Unity 在非 Development 版本中编译出 `ProfilerCounter` 和 `ProfilerCounterValue`。

### 将自定义定义模块添加到 性能分析器 窗口##add-a-custom-module-to-the-profiler-window

使用性能[分析器模块 Editor](/engine/6000.0/manual/analysis/profiler/customizing/creating-custom-modules/module-editor.md) 为可视化选择内置或新添加的计数器。要Open性能分析器模块Editor器：

1. 打开性能分析器 Window (**Window > Analysis > Performance Analytics**)。
2. 选择窗口左上角的性能分析器模块 Dropdown。单击齿轮图标，性能分析器模块 Editor 将在新建窗口中打开。
3. 选择 **Add**，然后从窗口右侧 ON 的**用户**列表中选择要可视化的计数器。

> **Important:**
>
> 如果未将Any数据加载到 性能分析器 窗口中，则在加载 性能分析器模块 Editor When，已创建的Any计数器都不会显示在 Available Counters 面板中。要查看自定义计数器，请[捕获或加载一些数据](/engine/6000.0/manual/profiler-collect-data.md)，其中使用性能分析器发送计数器，然后重新打开性能分析器模块 Editor。

然后，您可以在 性能分析器 窗口中与Other计数器一起View数据。有关更多信息，请参阅[创建自定义性能分析器模块](/engine/6000.0/manual/analysis/profiler/customizing/creating-custom-modules.md)。


**Module with custom counters in Profiler Window.:**
![](/api/media?file=/engine/6000.0/media/images/profiler-window-custom-module.png)

> **Note:**
>
> 声明为Static的计数器在初始化类型When在 C# 代码动态初始化，在实际初始化和使用之前可能不可用。这适用于编辑和播放模式。如果计数器未出现在性能分析器模块 Editor 中，请首先在几帧[使用性能分析器记录一些数据](/engine/6000.0/manual/analysis/profiler/profiling-applications/profiling-target-device.md)。

## 在构建的播放Player中可视化性能性能分析器数器##visualizing-profiler-counters-in-a-built-player

在构建的播放Player中运行Projectject，无法访问 性能分析器 窗口。但是，您可以在构建的 Player 中将计数器显示为 UI 元素。这意味着您可以在应用程序的版本中包含分析工具。

下图使用内置 Player 中的自定义 UI 在 Scene 的左上角显示计数器：


**Tanks game with custom information overlaid:**
![](/api/media?file=/engine/6000.0/media/images/Tanks-Runtime-Stats.png)

> **Note:**
>
> 并非所有性能分析器计数器在发布玩家（非 Development 版本）中都可用。使用 [`ProfilerRecorder.Valid`](/engine/6000.0/script-reference/unity/profiling/profilerrecorder/valid.md) 确定数据是否可用以及性能分析器是否可以记录它。或者，可以使用[`ProfilerRecorderHandle.GetAvailable`](/engine/6000.0/script-reference/unity/profiling/lowlevel/unsafe/profilerrecorderhandle/getavailable.md)来枚举所有可用性能分析器统计信息。

### 获取玩家中的计数器值##getting-counter-values-in-players

性能分析器 计数器可让您深入了解重要的游戏或引擎SystemMetrics。如果您有 Continuous 集成设置，或者希望在测试播放期间可视化应用程序中的 Key Performance Metrics，可以使用 [`ProfilerRecorder`](/engine/6000.0/script-reference/unity/profiling/profilerrecorder.md) API 获取自定义和内置性能分析器计数器值。

例如，以下脚本显示帧时间、Mono/IL2CPP 堆大小以及应用程序使用的总计内存。

```lang-cs
using System.Collections.Generic;
using System.Text;
using Unity.Profiling;
using UnityEngine;

public class StatsScript :MonoBehaviour
{
    string statsText;
    ProfilerRecorder systemMemoryRecorder;
    ProfilerRecorder gcMemoryRecorder;
    ProfilerRecorder mainThreadTimeRecorder;

    double GetRecorderFrameAverage（ProfilerRecorder 录制器）
    {
        var samplesCount = recorder.Capacity;
        if (samplesCount == 0)
            return 0;

        double r = 0;
        不安全
        {
            var samples = stackalloc ProfilerRecorderSample[samplesCount];
            recorder.CopyTo(samples, samplesCount);
            for (var i = 0; i < samplesCount; ++i)
                r += 样本]值;
            r /= samplesCount;
        }

        return r;
    }

    void OnEnable()
    {
        systemMemoryRecorder = ProfilerRecorder.StartNew(ProfilerCategory.Memory, "System Used Memory");
        gcMemoryRecorder = ProfilerRecorder.StartNew(ProfilerCategory.Memory, "GC Reserved Memory");
        mainThreadTimeRecorder = ProfilerRecorder.StartNew(ProfilerCategory.Internal, "Main Thread", 15);
    }

    void OnDisable()
    {
        systemMemoryRecorder.Dispose();
        gcMemoryRecorder.Dispose();
        mainThreadTimeRecorder.Dispose();
    }

    void Update()
    {
        var sb = new StringBuilder(500);
        sb.AppendLine($"Frame Time: {GetRecorderFrameAverage(mainThreadTimeRecorder) * (1e-6f):F1} ms");
        sb.AppendLine($"GC Memory: {gcMemoryRecorder.LastValue / (1024 * 1024)} MB");
        sb.AppendLine($"System Memory: {systemMemoryRecorder.LastValue / (1024 * 1024)} MB");
        statsText = sb.ToString();
    }

    void OnGUI()
    {
        GUI.TextArea(new Rect(10, 30, 250, 50), statsText);
    }
}
```

> **Important:**
>
> 使用 `ProfilerRecorder.Dispose` 可释放与`ProfilerRecorder`关联的非托管资源。

## 从 Editor 中的性能分析器帧数据获取计数器值##getting-counter-values-from-profiler-frame-data-in-the-editor

要在 Editor 中处理性能分析器帧数据时获取性能分析器计数器值，请使用 [`FrameDataView`](/engine/6000.0/script-reference/unityeditor/profiling/framedataview.md) API。

您可以使用 [`FrameDataView.GetCounterValueAsInt`](/engine/6000.0/script-reference/unityeditor/profiling/framedataview/getcountervalueasint.md)、[`FrameDataView.GetCounterValueAsLong`](/engine/6000.0/script-reference/unityeditor/profiling/framedataview/getcountervalueaslong.md)、[`FrameDataView.GetCounterValueAsFloat`](/engine/6000.0/script-reference/unityeditor/profiling/framedataview/getcountervalueasfloat.md) 和 [`FrameDataView.GetCounterValueAsDouble`](/engine/6000.0/script-reference/unityeditor/profiling/framedataview/getcountervalueasdouble.md) 来获取指定计数器的帧值，如下所示：

```lang-cs
using UnityEditor.Profiling;

类 示例
{
    Static 整型 ExtractMyCounterValue(FrameDataView frameData, 字符串 counterName)
    {
        var counterMarkerId = frameData.GetMarkerId(counterName);
        return frameData.GetCounterValueAsInt(counterMarkerId);
    }
}
```

## 其他资源##additional-resources

* [向代码中添加性能分析器计数器](/engine/6000.0/manual/analysis/profiler/customizing/adding-information-code/add-counters-code.md)
* [性能分析器模块 Editor 参考](/engine/6000.0/manual/analysis/profiler/customizing/creating-custom-modules/module-editor.md)
