Tuesday, November 26, 2013

Frame rate calculator for scenes in Unity3d

Standard
Hello All:

In our games, we often want to keep watch on the frame rate on which our game is being rendered on the device. In this post I will share a simple script to calculate and show frames on the screen for debugging.


Create a script and name it FrameRateCalculator. Copy and paste below code it the file.

        using UnityEngine;
using System.Collections;
using System;
public class FrameRateCalculator : MonoBehaviour
{
    public float updateInterval = 0.5F;
    float totalFramesInInterval = 0; 
    int frames = 0; 
    float timeleft;
    Rect StatRect;
    float fps;
    void Start()
    {
    }
    // Update is called once per frame
    void Update()
    {
        timeleft -= Time.deltaTime;
        totalFramesInInterval += Time.timeScale / Time.deltaTime;
        ++frames;
        if (timeleft <= 0.0f)
        {
            fps = totalFramesInInterval / frames;
            timeleft = updateInterval;
            totalFramesInInterval = 0.0F;
            frames = 0;
        }
    }
    void OnGUI()
    {
        StatRect = new Rect(Screen.width - 150, Screen.height - 50, 150, 25);
        GUI.Label(StatRect, "FPS: " + String.Format("{0:F2}", fps));
#if ENABLE_PROFILER
        StatRect.y += 25;
        string heap = "MEM: " + Profiler.GetMonoUsedSize() / 1024 + "k/" + Profiler.GetMonoHeapSize() + "k";
        GUI.Label(StatRect, heap);
#endif
    }
}

Attach the script to a blank game object in the scene. Save the scene and run the game. You will see frame rate and memory in the right bottom corner.

Hope this helps.

Thanks.

Thanks for printing this post. Hope you liked it.
Keep visiting and sharing.
Thanks,
Ashwani.

0 comments :

Post a Comment