Unity FPS Counter (Easy to Follow Tutorial for Beginners)
In this tutorial I’ll show you how to create a simple FPS counter for your Unity game. This counter will allow your to check and improve your game’s performance even when you export it. I’ll go over everything step-by-step and all code needed for each functionality to work will be provided here for free.
All scripts I made for this tutorial will be available in the Outro section.
Disclosure: Bear in mind that some of the links in this post are affiliate links and if you go through them to make a purchase I will earn a commission. Keep in mind that I link these companies and their products because of their quality and not because of the commission I receive from your purchases. The decision is yours, and whether or not you decide to buy something is completely up to you.
What is FPS?
FPS is acronym and it stands for Frames Per Second aka. frame-rate. It tells us how many images can our game render each second.
The more frames are rendered the smoother the experience is going to be. That’s because to achieve the illusion of continuous motion our game breaks down each event into smaller pieces and processes them one by one. This can be better explained through an example:
Let’s say you want to move an object (for example player character) and it moves at the speed of 5 meters per second in the forward direction.
If your game is running at 1 Frame per Second, player character will be at starting position during the first second and then it would basically teleport 5 meters forward the next second.
And if your game is running at 30 Frames per Second this movement would be broken down into 30 “parts” and for each part (frame) character would move 0.033 (1/30) meters forward which would give off the illusion of movement. Similarly to how notebook animations work.
Number of Frames per Second is calculated by dividing 1 (one second) by the time game needs to render one image (frame) which will highly depend on how good is your PC (newer computers will usually get better frame-rate) as well as the complexity of your game or the individual scene that you’re testing.
Prerequisites
First of all, here’s everything you need to know to go through this tutorial successfully:
- Basic knowledge of how to code (variables, if/else statements, loops, methods)
- Basic level of understanding of Unity (knowing what are scenes, game objects, components, inspector etc.)
If you’re total beginner and want to learn basics of Unity and programming here are some helpful resources for you as well:
- Check out “Intro to Game Development with Unity” course on Zenva Academy (https://academy.zenva.com/product/intro-to-unity-game-development/?a=294&campaign=Unity-for-beginners). In this course you’ll master the foundations of game development by exploring Unity engine & the C# programming language.
- To learn basics of C# check out this video by Code Monkey
- To get basic understanding of Unity check out their official Roll-a-ball tutorial (it’s very quick and easy to follow)
Also, you’ll need the following software installed on your computer to be able to follow along:
- Unity game engine (https://store.unity.com/#plans-individual)
- Visual Studio or VS Code or any other text editor that works with Unity (Visual Studio will automatically be installed with Unity if you keep the default settings)
Setting up the scene
I’m assuming you already have a Unity project for which you want to test FPS. But let’s just quickly glace over the setup that I have for this tutorial.
I’m using FPSLookAround script from my First Person Movement Tutorial. It does exactly what is says, it allows me to look around by moving my mouse.
Also, here’s the simple scene that I’ve set up to test everything:
I’ll test FPS for this scene in Unity
As you can see, my scene is very simple so this will most likely impact my FPS count in a positive way. For any real project that you’ll be working on FPS count will probably be much lower.
How to make a simple FPS counter
- Right click in Hierarchy
- Pick “Create Empty”
- Select newly created game object
- Rename it to “FPS Counter”
- Click on Add Component
- Type in “FPSCounter”
- Pick “New Script”
- And then “Create and Add”
This newly created script called FPSCounter will now be attached to “FPS Counter” game object and it will also appear in the project window.
Now to actually be able to see FPS count in our game view we first have to create a text object that is going to display it. To do so let’s:
- Select “FPS Counter” game object
- Right click on it
- Select UI -> Text
- Select this newly created Text object
- Find its Rect Transform component
- Set its width to 160 and height to 30
- Click on anchor option
Anchor preset options for Rect Transform
While holding Left Alt and Left Shift pick top-right option, like this:
Set anchor to top-right
Now let’s rename “Text” game object to “FPS Display”. Process is the same as with “FPS Counter”.
- Now find Text component of “FPS Display” game object
- Set its color to white
Now that we have everything ready we need to actually write a script that will calculate FPS and then display it through “FPS Display” game object.
So let’s open up FPSCounter script, it should look something like this:
Add new using statement at the line 4, like this:
This allows us to access UI Components in Unity. In this case we need it to access Text component of “FPS Display” game object to be able to change its content.
To actually access that Text component we need to have a reference to it in our script, so let’s add that in:
Reference to the Text component is a variable named fpsDisplay, which is a public variable meaning we can access it from Unity editor as well as from other scripts, and it holds value that has data type of Text.
Now, let’s calculate what’s the current FPS in our game.
Update method is called once per each frame and given that we want to continuously count our FPS that’s where our FPS calculation code needs to be.
Basically, on the first line we calculate current FPS and place that value in fps variable. On the second line of code we change content of Text component that’s attached to “FPS Display” game object to show the value we just calculated.
FPS is calculated by dividing 1 by Time.unscaledDeltaTime. Time.unscaledDeltaTime is the time our game needs to render one frame, so for example if our game is running at 60 Frames per Second this value will be 0.0166 (so it would need 16 milliseconds to render one frame) and dividing 1 (one second) by this value gives us the current FPS.
We use Time.unscaledDeltaTime instead of Time.deltaTime because we might want to change Time.timeScale while our game is running (for example to achieve slow motion) which is going to affect the value of Time.deltaTime. Here’s a more detailed explanation if you’re interested:
If we want to achieve slow motion we’re going to set Time.timeScale to some value that’s less than 1, let’s say we set it to 0.5 for the sake of simplicity. Let’s say that in this example our game is running at stable 60 FPS. In this case Time.unscaledDeltaTime would be 0.0166 as we already saw, but the value of Time.deltaTime would be half of that so 0.0083 which is calculated by multiplying Time.unscaledDeltaTime (0.0166) and Time.timeScale (0.5).
So when diving 1 (one second) with Time.deltaTime we would get that our game is running at 120 FPS instead of 60 FPS. Which isn’t the case so we instead use Time.unscaledDeltaTime in order to always get the true value. Hopefully it’s clear now.
On the second line inside the Update method we change the content of “FPS Display” Text component through its reference. We do so by setting its text property to a value of “” + fps (which basically converts float value of fps to a string so we can easily display it).
Now, let’s save this script and go back to the editor.
- Select “FPS Counter” game object
- Find FPSCounter script
As you can see there’s a empty slot named Fps Display requiring Text component.
Drag and drop “FPS Display” game object into that empty slot, like this:
Connecting FPS Counter Script with FPS Display
Now press Play to test it. In the top right corner you should hopefully be able to see your game’s current FPS count. It should look something like this:
Press play to see if your FPS Counter is working
As you can see my game is running at stable 60 Frames per Second.
Virtual Reality Mini-Degree
Become a professional VR developer. Learn to code and create 16 immersive games in Unity from the ground up. No prior programming experience is necessary to enroll.
VR Game Development Course on Zenva Academy
Limiting fps
In this section we’ll see how we can limit FPS in our games.
“Why limit FPS?” you may ask, and that’s a totally valid question. Here’re a couple of reasons:
- Testing – If you’re making a game for PC or Mobile there’re a lot of different devices people will use to play your game so you want to make sure that your game doesn’t break if it starts running at bellow 60 FPS.
- Catering to different refresh rates – Each monitor has a different refresh rate. It’s a waste of resources if your game runs at 200 FPS on a 120 Hertz monitor. In this case your computer calculates those additional 80 frames but then just throws them away because the monitor can’t keep up. So you might want to offer an option for players to limit their frame rate.
Now, let’s see how we can limit frame rate in Unity.
- Select “FPS Counter” game object
- Find FPSCounter script that’s attached to it and open it up
Add Start method to it like this:
This is all that we have to do, Unity does the rest for us. Of course, you can change targetFrameRate to any other value.
You can now save the script and go back to Unity if you want to test this out.
In this tutorial we won’t be using this feature so let’s comment it out for now so it allows us to calculate everything else properly.
Calculate average FPS
FPS may vary depending on the part of the level that you’re in and how many other game objects you have there so to let’s make our FPS Counter calculate what’s the average FPS.
Open up “FPSCounter” again and add these 3 variables at the top of it:
As you can see first variable that we added is a public reference to a Text component. Later on we’ll make a Text object that will displays an average FPS and this variable is going to be our reference to it.
Variable framesPassed is the total number of frames that has passed since we started calculating the average FPS.
Variable fpsTotal is the sum of all FPS values since we started calculating the average.
Now to calculate the average let’s add this code to Update method:
As you can see we’re adding current FPS to the value of fpsTotal. Then we increase framesPassed by one. Then we calculate average FPS and display it through averageFPSDisplay Text component.
We’re going to get the average FPS by dividing fpsTotal with framesPassed.
Now save the script and go back to Unity editor.
- Select “FPS Counter” game object
- Expand it
- Right click on Canvas game object
- Select UI > Text
- Rename it to “FPS Average Display”
Now we need to anchor this text object to top right corner of the screen, to do this we have to do the same thing we did to “FPS Display” text object.
- Find its Rect Transform component
- Click on anchor option
- While holding Left Alt and Left Shift pick top right option
For this Rect Transform component also set the value of Pos Y to be -30 so that it doesn’t overlap with fps display.
- Find Text component
- Set its color to white
Now we need to connect this new text object to FPSCounter script.
- Select the “FPS Counter” game object
- Drag and drop “FPS Average Display” into “Average FPS Display” slot
Press Play and move mouse around to test it.
Calculate min and max FPS
To see if there are some bumps in FPS while we’re playing we should also save min and max FPS values.
First of all open up FPSCounter script again and add these 4 variables at the top:
Again, we first have 2 references to Text components that will display minimum and maximum FPS values respectively.
Then we define variables that are actually going to hold min and max FPS values. We set minFPS value to Mathf.Infinity (largest possible number) because if we were to set it to let’s say 0 no other value of FPS is going to be lower than it and our minFPS is always going to stay at 0 which isn’t true.
We also defined maxFPS variable and for now we set it’s value to 0.
Now let’s calculate max FPS value and display it on the screen. To do so add this code to the Update method:
To get the maximum FPS value we first have to check if the current FPS (value of fps variable) is larger than maxFPS (which is 0 at the beginning).
We also want to check if 10 frames have already passed. We do so because we want to avoid the part of the game when the scene is still loading and the FPS is very unstable.
If these 2 conditions are met we set value of maxFPS to be equal to fps. And we change content of maxFPSDisplay Text component so that it displays maximum FPS.
Now let’s calculate minimum FPS. To do so add this code inside the Update method bellow what we previously wrote:
As you can see this code works basically the same as the one above the only difference is that we check if current FPS is lower than minFPS (which is equal to Infinity at the beginning). If this condition is met and 10 frames have passed we want to set minFPS to current FPS (fps variable value) and display it through minFPSDisplay Text component.
Now save the script and go back to Unity editor.
- Select “FPS Counter” game object
- Expand it
- Right click on Canvas game object
- Select UI > Text
- Rename this new object it to “Max FPS Display”
Now we need to anchor this text object to top-right corner of the screen, to do this we have to repeat what we did to all other Text game objects so far.
- Find its Rect Transform component
- Click on anchor option
- While holding Left Alt and Left Shift pick top-right option
For this Rect transform component also set the value of Pos Y to be -90
- Find Text component
- Set its color to white
Do this once again but this time rename new object to “Min FPS Display” and also set its Rect Transform Pos Y value to -60
Now let’s connect these two Text objects with FPSCounter script.
- Select “FPS Counter”
- Drag and drop “Max FPS Display” game object into “Max FPS Display” slot
- Drag and drop “Min FPS Display” game object into “Min FPS Display” slot
Press Play and move mouse around to test.
Final version of this counter should look something like this:
Final version showing Current, Average, Min and Max FPS in the top-right corner
Outro
If you followed this tutorial step-by-step you should now have working FPS Counter that displays current FPS, average FPS as well as minimum and maximum FPS values. If you have any question feel free to ask down in the comments bellow.
Script that I’ve made for this tutorial can be downloaded from here: FPS Counter Script
Hopefully, this tutorial helped you. If it did definitely Subscribe to my Newsletter I plan on making more game dev tutorials coming soon.
Thanks for reading!
Multiplayer Game Development Mini-Degree
The world’s first on-demand curriculum to teach ANYONE how to code and build impressive multiplayer games with Unity and Photon – build a battle royale, RPG, turn-based game and more!
Multiplayer Game Development Course on Zenva Academy
Источник