Unity脚本获取内存和FPS

时间:2023-03-09 15:35:43
Unity脚本获取内存和FPS

using System;

using System.Collections.Generic;

using UnityEngine;





public class Debugger : MonoBehaviour

{

    void Start()

    {

        timeleft = updateInterval;

    }

    void Update()

    {

        UpdateUsed();

        UpdateFPS();

    }

    //Memory

    private string sUserMemory;

    private string s;

    public bool OnMemoryGUI;

    private uint MonoUsedM;

    private uint AllMemory;

    [Range(0, 100)]

    public int MaxMonoUsedM = 50;

    [Range(0, 400)]

    public int MaxAllMemory = 200;

    void UpdateUsed()

    {

        sUserMemory = "";

        MonoUsedM = Profiler.GetMonoUsedSize() / 1000000;

        AllMemory = Profiler.GetTotalAllocatedMemory() / 1000000;





        sUserMemory += "MonoUsed:" + MonoUsedM + "M" + "\n";

        sUserMemory += "AllMemory:" + AllMemory + "M" + "\n";

        sUserMemory += "UnUsedReserved:" + Profiler.GetTotalUnusedReservedMemory() / 1000000 + "M" + "\n";





        s = "";

        s += " MonoHeap:" + Profiler.GetMonoHeapSize() / 1000 + "k";

        s += " MonoUsed:" + Profiler.GetMonoUsedSize() / 1000 + "k";

        s += " Allocated:" + Profiler.GetTotalAllocatedMemory() / 1000 + "k";

        s += " Reserved:" + Profiler.GetTotalReservedMemory() / 1000 + "k";

        s += " UnusedReserved:" + Profiler.GetTotalUnusedReservedMemory() / 1000 + "k";

        s += " UsedHeap:" + Profiler.usedHeapSize / 1000 + "k";

    }





    //FPS

    float updateInterval = 0.5f;

    private float accum = 0.0f;

    private float frames = 0;

    private float timeleft;

    private float fps;

    private string FPSAAA;

    [Range(0, 150)]

    public int MaxFPS;

    void UpdateFPS()

    {

        timeleft -= Time.deltaTime;

        accum += Time.timeScale / Time.deltaTime;

        ++frames;





        if (timeleft <= 0.0)

        {

            fps = accum / frames;

            FPSAAA = "FPS: " + fps.ToString("f2");

            timeleft = updateInterval;

            accum = 0.0f;

            frames = 0;

        }

    }

    void OnGUI()

    {

        if (OnMemoryGUI)

        {

            GUI.color = new Color(1, 0, 0);

            GUI.Label(new Rect(10, 10, 200, 60), sUserMemory);

            GUI.Label(new Rect(10, 60, 100, 30), FPSAAA);

            if (MonoUsedM > MaxMonoUsedM)

            {

                GUI.backgroundColor = new Color(1, 0, 0);

                GUI.Button(new Rect(0, 0, 1024, 1024), "MonoUsedM Waming!!内存不足");

            }

            if (AllMemory > MaxAllMemory)

            {

                GUI.backgroundColor = new Color(1, 0, 1);

                GUI.Button(new Rect(0, 0, 1024, 1024), "AllMemory Waming!!内存堪忧");

            }

            if (fps > MaxFPS)

            {

                GUI.backgroundColor = new Color(1, 0.4f, 0.5f);

                GUI.Button(new Rect(0, 0, 1024, 1024), "FPS Waming!!");

            }

        }





    }

   

}