Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Frames Per Second Prefab

TwitterFacebookRedditLinkedInHacker News

When building a game, it is often a good idea to know your frames per second (fps) during the testing phase. It is even more important to know this when building for mobile devices that may not have the high specifications that modern computers have.

The easiest method to have the frames per second display is to create a prefab that you can recycle across all your game scenes.

In your Unity3D project, create a new GameObject that is a GUIText. Let’s rename it to FPS in order to keep your project clean.

FPS GUIText GameObject

Because I like to see my frames per second in the lower right portion of the screen I gave it a position of (0.96, 0.04, 0), an anchor of lower right, and an alignment of right. Remember that GUIText positions can only fall between 0 and 1. With the positioning information I provided, the text will always appear in the same position regardless of screen size.

When configuring your font information, leave the font size at zero because we will be setting this in a script. Setting the font size as a constant in the project editor will result in different font sizes across devices. We want it to be the same size across all devices.

Go ahead and add a new C# script component to your GUIText object. Add the following code to the script.

using UnityEngine;
using System.Collections;

public class FPS : MonoBehaviour {

    public float updateInterval = 0.5F;
    private float totalFPS = 0;
    private int totalFrames = 0;
    private float timeUntilUpdate;

    void Start () {
        guiText.fontSize = Mathf.RoundToInt(Camera.main.pixelHeight / 30f);
        guiText.alignment = TextAlignment.Right;
        guiText.anchor = TextAnchor.LowerRight;
        guiText.text = "0 FPS";
        timeUntilUpdate = updateInterval;
    }

    void Update () {
        timeUntilUpdate -= Time.deltaTime;
        totalFPS += Time.timeScale / Time.deltaTime;
        ++totalFrames;
        if(timeUntilUpdate <= 0.0) {
            float fps = totalFPS / totalFrames;
            guiText.text = System.String.Format("{0:F2} FPS", fps);
            timeUntilUpdate = updateInterval;
            totalFPS = 0.0F;
            totalFrames = 0;
        }
    }
}

When you’re done, drag the FPS object from the project hierarchy into your prefabs directory. This will make it incredibly simple to recycle your FPS object in any desired scene.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.