要添加性能分析器计数器,请创建脚本来执行以下操作:
这些部分中的代码示例添加了一个性能分析器计数器,用来跟踪 Unity 为游戏对象的拖尾效果的每个实例创建的粒子总数。在这些示例中,游戏对象的名称为“Tank”。
一些示例会用到 Profiling Core 包,在开始之前必须安装该包。因为 Unity Profiling Core 是核心包,所以在 Package Manager__ UI__(即用户界面,User Interface)让用户能够与您的应用程序进行交互。Unity 目前支持三种 UI 系统。更多信息
See in Glossary 中无法找到。要安装包,请执行以下操作之一:
要新建计数器:
重要提示:创建计数器时,必须指定新计数器所属的性能分析器类别。可以使用 ProfilerCategory 类中的现有 Unity 类别来完成此操作。以下示例中的脚本使用现有的 ProfilerCategory.Scripts 类别。
性能分析器计数器 API 支持推送和拉取操作。您可以将计数器的值推送到性能分析器,或者性能分析器可以在帧末尾拉取该值。
如果您的数据不经常更改,例如每帧更改一次,请使用 ProfilerCounter API 将计数器数据推送到性能分析器。如果您的数据每帧更改多次,请使用 ProfilerCounterValue API。这样能使性能分析器在帧结束时自动获取最后一个值。
以下示例脚本定义 ProfilerCounterValue TankTrailParticleCount,其中名称为“Tank Trail Particles”,单位为 ProfilerMarkerDataUnit.Count:
public 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);
}
选项 FlushOnEndOfFrame 和 ResetToZeroOnFlush 会自动将计数器发送到性能分析器数据流,并在帧末尾将计数 (Count) 值重置为零。
要更新计数器的值,请创建一个 MonoBehaviour 脚本来设置已定义的计数器的值。
以下 MonoBehaviour 脚本在 Update 函数中计算每一帧属于指定游戏对象的拖尾粒子数量。为此,它使用名为 TankTrailParticleCount 的计数器。
以下示例脚本还会在检视面板中创建一个名为拖尾粒子系统 (Trail Particle System, m_TrailParticleSystem) 的公共属性:
using UnityEngine;
class TankMovement : MonoBehaviour
{
public ParticleSystem m_TrailParticleSystem;
void Update()
{
GameStats.TankTrailParticleCount.Value += m_TrailParticleSystem.particleCount;
}
}
要通过代码在自定义性能分析器模块中显示性能分析器计数器,必须创建新的 ProfilerModule 脚本并定义该模块的属性,包括显示的计数器、名称和图标。有关如何执行此操作的信息,请参阅在代码中创建性能分析器模块。