【unity小技巧】自定义脚本实现在游戏内实时读取GPU设备信息和计算游戏的FPS(帧率/帧速)值

发布于:2025-07-20 ⋅ 阅读:(19) ⋅ 点赞:(0)

前言

在游戏开发过程中,实时监控设备性能和运行状态是优化游戏体验的关键环节。本文将介绍两个核心性能监测工具的实现:设备类型显示UI和FPS计数器,它们为开发者提供了宝贵的运行时诊断信息。

设备类型显示UI

using UnityEngine;
using UnityEngine.UI;

public class DeviceTypeUI : MonoBehaviour
{
    void Start()
    {
        // 获取图形设备信息
        string deviceName = SystemInfo.graphicsDeviceName;  // 图形设备GPU名称(如"NVIDIA GeForce RTX 3080")
        string deviceTypeName = SystemInfo.graphicsDeviceType.ToString(); // 图形设备GPU类型(如"Direct3D11")
        // int gpuMemory = SystemInfo.graphicsMemorySize;       // 显存大小(MB)
		// string gpuVersion = SystemInfo.graphicsDeviceVersion; // 驱动版本
		
        // 将设备信息显示在UI文本组件上
        GetComponent<Text>().text = deviceName + "\n" + deviceTypeName;
    }
}

FPS(帧率/帧速)计数器

using UnityEngine;
using UnityEngine.UI;

namespace UnityStandardAssets.Utility
{
    [RequireComponent(typeof (Text))]
    public class FPSCounter : MonoBehaviour
    {
        const float fpsMeasurePeriod = 0.5f; // FPS测量周期(秒)
        private int m_FpsAccumulator = 0;    // FPS累计器
        private float m_FpsNextPeriod = 0;   // 下一次测量时间点
        private int m_CurrentFps;            // 当前FPS值
        const string display = "{0} FPS";    // 显示格式
        private Text m_GuiText;              // UI文本组件


        private void Start()
        {
            // 初始化下一次测量时间点
            m_FpsNextPeriod = Time.realtimeSinceStartup + fpsMeasurePeriod;
            // 获取Text组件
            m_GuiText = GetComponent<Text>();
        }


        private void Update()
        {
            // 测量平均帧率
            m_FpsAccumulator++;
            // 到达测量时间点时计算FPS
            if (Time.realtimeSinceStartup > m_FpsNextPeriod)
            {
                m_CurrentFps = (int) (m_FpsAccumulator/fpsMeasurePeriod); // 计算FPS
                m_FpsAccumulator = 0;             // 重置计数器
                m_FpsNextPeriod += fpsMeasurePeriod; // 设置下一个测量点
                m_GuiText.text = string.Format(display, m_CurrentFps); // 更新显示
            }
        }
    }
}

结果
在这里插入图片描述


专栏推荐

地址
【unity游戏开发入门到精通——C#篇】
【unity游戏开发入门到精通——unity通用篇】
【unity游戏开发入门到精通——unity3D篇】
【unity游戏开发入门到精通——unity2D篇】
【unity实战】
【制作100个Unity游戏】
【推荐100个unity插件】
【实现100个unity特效】
【unity框架/工具集开发】
【unity游戏开发——模型篇】
【unity游戏开发——InputSystem】
【unity游戏开发——Animator动画】
【unity游戏开发——UGUI】
【unity游戏开发——联网篇】
【unity游戏开发——优化篇】
【unity游戏开发——shader篇】
【unity游戏开发——编辑器扩展】
【unity游戏开发——热更新】
【unity游戏开发——网络】

完结

好了,我是向宇,博客地址:https://xiangyu.blog.csdn.net,如果学习过程中遇到任何问题,也欢迎你评论私信找我。

赠人玫瑰,手有余香!如果文章内容对你有所帮助,请不要吝啬你的点赞评论和关注,你的每一次支持都是我不断创作的最大动力。当然如果你发现了文章中存在错误或者有更好的解决方法,也欢迎评论私信告诉我哦!
在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到