Unity 实时 CPU 使用率监控

在 Unity 中,我们可以通过获取 CPU 使用率来优化性能,或者为用户提供性能监控的反馈信息。本文将指导你如何在 Unity 中实现一个简单的实时 CPU 使用率监控器。

前置条件


  • Unity3D 2018 或更高版本
  • C# 编程基础

项目设置


首先,你需要在 Unity 项目中创建一个 UI 文本组件(TextMeshProUGUI)来显示 CPU 使用率。

  1. 创建一个空的 GameObject,将 CpuUsage 脚本挂载到该 GameObject 上。
  2. 在该 GameObject 上添加一个 TextMeshProUGUI 组件,用来显示 CPU 使用率。

脚本说明


下面是 CpuUsage 脚本的代码实现,代码中使用了 System.Diagnostics 来获取 CPU 使用率,并通过多线程更新实时值,避免主线程阻塞。

cs 复制代码
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using TMPro;
using UnityEngine;

[RequireComponent(typeof(TextMeshProUGUI))]
public class CpuUsage : MonoBehaviour
{
    private TextMeshProUGUI labelText;

    [SerializeField] private float updateInterval = 1;
    [SerializeField] private int processorCount;
    private float cpuUsage;
    private Thread cpuThread;
    private float lasCpuUsage;

    private void Awake()
    {
        labelText = GetComponent<TextMeshProUGUI>();
    }

    private void Start()
    {
        Application.runInBackground = true;

        labelText.text = "CPU使用率:0 %";

        cpuThread = new Thread(updateCPUUsage)
        {
            IsBackground = true,
            Priority = System.Threading.ThreadPriority.BelowNormal
        };

        cpuThread.Start();
    }

    private void OnValidate()
    {
        processorCount = SystemInfo.processorCount / 2;
    }

    private void OnDestroy()
    {
        cpuThread?.Abort();
    }

    private void Update()
    {
        if (Mathf.Approximately(lasCpuUsage, cpuUsage)) return;
        if (cpuUsage < 0 || cpuUsage > 100) return;
        labelText.text = "CPU使用率:" + cpuUsage.ToString("F1") + " %";
        lasCpuUsage = cpuUsage;
    }

    private void updateCPUUsage()
    {
        var lastCpuTime = new TimeSpan(0);

        while (true)
        {
            var cpuTime = new TimeSpan(0);
            var AllProcesses = Process.GetProcesses();
            cpuTime = AllProcesses.Aggregate(cpuTime, (current, process) => current + process.TotalProcessorTime);
            var newCPUTime = cpuTime - lastCpuTime;
            lastCpuTime = cpuTime;
            cpuUsage = 100f * (float)newCPUTime.TotalSeconds / updateInterval / processorCount;
            Thread.Sleep(Mathf.RoundToInt(updateInterval * 1000));
        }
    }
}

代码解析

  1. 组件依赖与初始化

    • 使用 TextMeshProUGUI 显示 CPU 使用率信息,Awake() 方法获取该组件。
    • OnValidate() 方法会自动计算处理器的数量(我们默认处理器数量的一半来进行显示)。
  2. 实时更新 CPU 使用率

    • Start() 方法中,我们创建了一个后台线程 cpuThread,它会定时更新 CPU 使用率。
    • updateCPUUsage() 方法通过 Process.GetProcesses() 获取系统中所有进程的 CPU 使用时间并计算 CPU 的总使用时间。
  3. UI 更新

    • Update() 方法每帧检查 CPU 使用率是否有变化,如果有变化则更新 UI 显示。
    • cpuUsage 为计算出的 CPU 使用率,labelText.text 用来更新显示在 UI 上的文字。
  4. 多线程处理

    • 使用多线程避免阻塞主线程。cpuThread 是一个后台线程,定时获取 CPU 使用时间。
  5. 清理与停止

    • OnDestroy() 方法中,如果线程仍然存在,将会被终止,避免内存泄漏。

性能与优化

  • updateInterval 控制了 CPU 使用率更新的频率,默认为 1 秒。你可以根据实际需求调整更新间隔。
  • 为了避免频繁更新 UI,可以通过 Mathf.Approximately() 方法比较当前和上次的 CPU 使用率是否相同,避免不必要的 UI 更新。

测试

  1. 挂载脚本到一个 GameObject 上。
  2. 确保你的 UI 上有一个 TextMeshProUGUI 组件。
  3. 运行游戏并观察屏幕上的 CPU 使用率。
相关推荐
风酥糖7 小时前
Godot游戏练习01-第21节-优化游戏菜单,增加选项
游戏·游戏引擎·godot
C蔡博士7 小时前
Unity2D物理系统-从入门到实战优化
unity·游戏引擎·rigidbody2d
mxwin14 小时前
Unity Shader 顶点动画:在顶点着色器中实现风吹草动、河流波动、布料模拟
unity·游戏引擎·shader·着色器
DowneyJoy15 小时前
【Unity3D补充知识点】常用数据结构分析-集合(List<T>)
数据结构·unity·c#·list
DowneyJoy16 小时前
【Unity3D补充知识点】常用数据结构分析-数组(Array)
数据结构·unity·c#
w-白兰地16 小时前
配置Unity中的ADB环境变量
unity·adb·游戏引擎
mxwin17 小时前
Unity Shader 几何着色器:动态生成图元与顶点拓扑修改
unity·游戏引擎·着色器
呆呆敲代码的小Y18 小时前
【Unity-AI开发篇】| 游戏中接入DeepSeek实现AI对话,完整详细步骤
人工智能·游戏·unity·ai·游戏引擎·u3d·deepseek
相信神话20212 天前
第四章:Godot 4.6 核心概念与开发环境搭建
游戏引擎·godot·2d游戏编程·godot4·2d游戏开发
代数狂人2 天前
在Godot中应用面向对象原则:C#脚本实践
c#·游戏引擎·godot