For the past few days, I have been struggling a lot with optimization problems in the game.
I’d be running the game from the Unity editor, and for the most part, the game would be running at around 100 FPS. However, every once in a while, there the framerate would drop down to 30 or 40, and this would cause a very noticeable lag in a gameplay.
I opened up Unity profiler, and noticed these massive spikes in CPU usage:
When I clicked on the spikes to see what exactly was causing this, most of it was caused by GC.Collect (garbage collection) under GUI.repaint.
This was really confusing to me, as I have very minimal UI in the game.
However, I started doing research, and it turns out that just by having void OnGUI in your script, even if it’s not drawing anything, will cause allocation. At some point, all of these garbage will need to get collected.
I then remembered that earlier in development, when trying to debug different triggers and switches, I would use OnGUI to let me know when different states have changed. After I got everything working, I commented out what was inside OnGUI, but left the actual call there.
So in a bunch of scripts, I had something like this:
1 2 3 | void OnGUI(){ //draw something } |
And of course, each of these was generating garbage, which then had to be collected.
After deleting this in all the scripts I could find, performance increased significantly!
So all I did, was delete a bunch of code that already wasn’t doing anything, and it fixed my performance problem.