Unity profiler — the forgotten child of game developement
Objective: Show how the Unity profiler can help with detecting where your game might need some performance boosts
My latest game The Departure I routinely use coroutines to delay a function or just to display some text for a set amount of time. One thing that I didn’t realise was that each time I am using the following code:
I am creating garbage that the game has to deal with. Instead of creating a new WaitForSeconds I instead decided to cache it and then use that.
This means I only create two new waitforseconds instead of 6 in the particular method I am going to show.
The text that is being shown and then turned off is some tutorial text that appears on the start of the game. This was causing small spike in the profiler, which I will show now.
To activate the profiler window inside of Unity you need to go to window -> analysis -> profiler.
Doing this will bring up the profiler. There are a lot of options to look at here but for this article I will be looking at the CPU usage section.
At the bottom of the screenshot you can see Hierarchy. You will need to change to Hierarchy to see what is happening when the game is running. You can pause the game when it is running and click on any frame that is causing a spike. It will also tell you how much data is being used and you can get down into the specific action that is causing the spike.
Looking at the screenshot above might be a little strange but I will go through what I am seeing here in my game. I am getting a big spike in this frame and that is being caused by the player loop. It is using 9.3kb of garbage collection every frame. It might not sound a lot but if you are running at 60 fps then times 9.3kb by 60 and it will start to add up.
Looking down in the data available I can see that I my OpenDoor script is causing the spike and it is tied to a console log. I am mistakenly using a debug.log without any checks and it is being called every frame. This is important as it is vital that any console logs you have are removed from the code once you’re finished with them.
I went into the script and removed the debug.log and I now do not that garbage collection happening which is great. Little changes like this can help a tonne when it comes to shipping the game.
Always remember to remove your debug.logs.
Another thing to consider is that it might be the editor that is causing some performance dips. If that is the case then you should make a development build of the game and run it (build n run), you will then be able to run the game in a separate window but the profiler will still be connected to the game running.
Make sure to tick the boxes above in the build settings of the project and click build and run. This will make sure to autoconnect the profiler to the game as it is running on the machine.