Search Unity

Display Actual CPU Usage On A UI Canvas

Discussion in 'Scripting' started by KnightRiderGuy, Jul 28, 2017.

  1. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    515
    Is there a way in C# to display the actual CPU usage on a UI Canvas using either a Slider or UI Text
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
  3. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    515
    @Kiwasi
    Thanks I tried that out and it just reads my CPU as 100%And My ram at 0MB

    This is the script I used including the UI Text, I'm trying it on a Mac Does it only work on PC

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Diagnostics;
    4.  
    5. using UnityEngine.UI;
    6.  
    7. public class ProfilingScript : MonoBehaviour
    8. {
    9.     PerformanceCounter cpuCounter;
    10.     PerformanceCounter ramCounter;
    11.  
    12.     public Text cpuText;
    13.     public Text ramText;
    14.  
    15.  
    16.  
    17.     void Start()
    18.     {
    19.         cpuCounter = new PerformanceCounter();
    20.  
    21.         cpuCounter.CategoryName = "Processor";
    22.         cpuCounter.CounterName = "% Processor Time";
    23.         cpuCounter.InstanceName = "_Total";
    24.  
    25.         ramCounter = new PerformanceCounter("Memory", "Available MBytes");
    26.     }
    27.  
    28.     void Update()
    29.     {
    30.         print(getCurrentCpuUsage());
    31.         //cpuText.text = cpuCounter;
    32.         cpuText.text = "CPU: " + getCurrentCpuUsage ();
    33.  
    34.         print(getAvailableRAM());
    35.         ramText.text = "RAM: " + getAvailableRAM ();
    36.     }
    37.  
    38.     public string getCurrentCpuUsage(){
    39.         return cpuCounter.NextValue()+"%";
    40.     }
    41.  
    42.     public string getAvailableRAM(){
    43.         return ramCounter.NextValue()+"MB";
    44.     }
    45. }
     

    Attached Files:

    Last edited: Jul 29, 2017