可使用 ProfilerRecorder API 而不是 FrameTimingManager C# API 读取 FrameTimingManager 的值。这样做的好处是,使用 ProfilerRecorder API 时,FrameTimingManager 仅在将记录器附加到特定计数器时对值进行记录。此行为使您能够控制进行数据收集的计数器,从而减少 FrameTimingManager 对性能的影响。
以下示例展示了如何使用 ProfilerRecordAPI 仅对 CPU 主线程帧时间变量进行跟踪:
using Unity.Profiling;
using UnityEngine;
public class ExampleScript : MonoBehaviour
{
string statsText;
ProfilerRecorder mainThreadTimeRecorder;
void OnEnable()
{
mainThreadTimeRecorder = ProfilerRecorder.StartNew(ProfilerCategory.Internal, "CPU Main Thread Frame Time");
}
void OnDisable()
{
mainThreadTimeRecorder.Dispose();
}
void Update()
{
var frameTime = mainThreadTimeRecorder.LastValue;
// Your code logic here
}
}