将性能分析器计数器添加到代码中
Collect specific statistics with profiler counters.
阅读时间4 分钟最后更新于 1 个月前
要添加性能分析器计数器,请创建脚本来执行以下操作:
这些部分中的代码示例添加了一个性能分析器计数器,用来跟踪 Unity 为游戏对象的拖尾效果的每个实例创建的粒子总数。在这些示例中,游戏对象的名称为“Tank”。
资质要求
一些示例会用到 Profiling Core 包,在开始之前必须安装该包。因为 Unity Profiling Core 是核心包,所以在 Package Manager UI 中无法找到。要安装包,请执行以下操作之一:
创建和定义计数器
要新建计数器:
- 编写一个脚本来定义新计数器的值类型。
- 向此类型分配名称和单位。
**重要提示:**创建计数器时,必须指定新计数器所属的性能分析器类别。可以使用 类中的现有 Unity 类别来完成此操作。以下示例中的脚本使用现有的 类别。
ProfilerCategoryProfilerCategory.Scripts性能分析器计数器 API 支持推送和拉取操作。您可以将计数器的值推送到性能分析器,或者性能分析器可以在帧末尾拉取该值。
如果您的数据不经常更改,例如每帧更改一次,请使用 API 将计数器数据推送到性能分析器。如果您的数据每帧更改多次,请使用 API。这样能使性能分析器在帧结束时自动获取最后一个值。
ProfilerCounterProfilerCounterValue以下示例脚本定义 ,其中名称为“Tank Trail Particles”,单位为 ProfilerMarkerDataUnit.Count:
ProfilerCounterValueTankTrailParticleCountpublic static class GameStats{ public static readonly ProfilerCategory TanksCategory = ProfilerCategory.Scripts; public const string TankTrailParticleCountName = "Tank Trail Particles"; public static readonly ProfilerCounterValue<int> TankTrailParticleCount = new ProfilerCounterValue<int>(TanksCategory, TankTrailParticleCountName, ProfilerMarkerDataUnit.Count, ProfilerCounterOptions.FlushOnEndOfFrame | ProfilerCounterOptions.ResetToZeroOnFlush);}
选项 和 会自动将计数器发送到性能分析器数据流,并在帧末尾将计数 (Count) 值重置为零。
FlushOnEndOfFrameResetToZeroOnFlush更新计数器的值
要更新计数器的值,请创建一个 MonoBehaviour 脚本来设置已定义的计数器的值。
以下 MonoBehaviour 脚本在 Update 函数中计算每一帧属于指定游戏对象的拖尾粒子数量。为此,它使用名为 的计数器。
TankTrailParticleCount以下示例脚本还会在检视面板中创建一个名为拖尾粒子系统 (Trail Particle System, ) 的公共属性:
m_TrailParticleSystemusing UnityEngine; class TankMovement : MonoBehaviour { public ParticleSystem m_TrailParticleSystem; void Update() { GameStats.TankTrailParticleCount.Value += m_TrailParticleSystem.particleCount; } }
将性能分析器计数器添加到自定义性能分析器模块
要通过代码在自定义性能分析器模块中显示性能分析器计数器,必须创建新的 脚本并定义该模块的属性,包括显示的计数器、名称和图标。有关如何执行此操作的信息,请参阅在代码中创建性能分析器模块。
ProfilerModule