unity 增加系统时间显示、FPS帧率、ms延迟

本文介绍了一个在Unity游戏引擎中使用C#编写的Frame类脚本,用于记录帧数、计算帧率,并在GUI上显示实时性能信息。脚本被挂载到相机上,帮助开发者监控游戏性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using UnityEngine;

public class Frame : MonoBehaviour
{
    // 记录帧数
    private int _frame;
    // 上一次计算帧率的时间
    private float _lastTime;
    // 平均每一帧的时间
    private float _frameDeltaTime;
    // 间隔多长时间(秒)计算一次帧率
    private float _Fps;
    private const float _timeInterval = 0.5f;

    void Start()
    {
        _lastTime = Time.realtimeSinceStartup;
    }

    void Update()
    {
        FrameCalculate();
    }

    private void FrameCalculate()
    {
        _frame++;
        if (Time.realtimeSinceStartup - _lastTime < _timeInterval)
        {
            return;
        }

        float time = Time.realtimeSinceStartup - _lastTime;
        _Fps = _frame / time;
        _frameDeltaTime = time / _frame;

        _lastTime = Time.realtimeSinceStartup;
        _frame = 0;
    }

    private void OnGUI()
    {
        string msg = string.Format("<color=red><size=30>FPS:{0}   ms:{1}</size></color>",(int) _Fps , (int)(_frameDeltaTime *1000));
        GUI.Label(new Rect(Screen.width-230, 0, 500, 150), msg);

        var timeNow = System.DateTime.Now;
        string time = string.Format("<color=green><size=30>{0}</size></color>", timeNow);
        GUI.Label(new Rect(Screen.width/2-200, 2, 600, 50), time);
    }
}

将脚本挂载到相机上面

在这里插入图片描述

效果

在这里插入图片描述