46 lines
1.3 KiB
C#
46 lines
1.3 KiB
C#
using TMPro;
|
|
using UnityEngine;
|
|
|
|
/// <summary>
|
|
/// 把实时帧率写进 target 指定的文本,用来在真机上直接看性能。
|
|
/// 节点引用一律在 Inspector / 预制体里指定,代码里不按名字查找节点。
|
|
/// </summary>
|
|
[DisallowMultipleComponent]
|
|
public class FpsDisplay : MonoBehaviour
|
|
{
|
|
[Tooltip("显示帧率的文本,必须在 Inspector 里指定")]
|
|
[SerializeField] private TMP_Text target;
|
|
|
|
[Tooltip("刷新间隔(秒)。0.25 = 每秒刷 4 次,数字不会跳得太厉害")]
|
|
[SerializeField] private float updateInterval = 0.25f;
|
|
|
|
[Tooltip("文本格式,{0} 是帧率数值。例:FPS:{0:0}f/s")]
|
|
[SerializeField] private string format = "FPS:{0:0}f/s";
|
|
|
|
private float _accumulatedTime;
|
|
private int _frames;
|
|
|
|
private void Awake()
|
|
{
|
|
if (target == null)
|
|
Debug.LogError("[FpsDisplay] 没有指定显示帧率的文本(target),请在 Inspector 里拖入。", this);
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
if (target == null)
|
|
return;
|
|
|
|
_accumulatedTime += Time.unscaledDeltaTime;
|
|
_frames++;
|
|
|
|
if (_accumulatedTime < updateInterval)
|
|
return;
|
|
|
|
target.text = string.Format(format, _frames / _accumulatedTime);
|
|
|
|
_accumulatedTime = 0f;
|
|
_frames = 0;
|
|
}
|
|
}
|