Textures in Unity are easy. Super easy. Until you mix them with editor scripts. That's when all hell breaks looks. For you see, with C#, you cannot clean up your memory by yourself the way you can in something like C or Rust; you're at the mercy of the Mono Runtime. Now this makes games pretty easy to write, but when you work outside the game runtime and start writing editor scripts, things can get out of hand.
The short of it is, if you make a texture, and it's not passed to another texture variable, clean it up. Use DestroyImmediate or else you will be leaking dozens of megabytes every GUI update cycle. This sucks very badly. For Tyle, my tile editor, this problem was pretty nasty and the only way to see if I was making any improvements on the texture leaking was with the Unity Profiler. The profiler rocks, but is only available in Unity Pro, so I didn't always have access to it. This means that Tyle had some nasty leaks for many many commits.
The worst was with the selection texture. If you hover over a tile with the mouse, you'll get a nice transparent texture over the map texture to show you where you're selecting. Neat huh? Well turns out it wasn't so neat. because I wasn't destroying the previous texture before assigning a new one (it would change color or disappear depending on various settings), it leaked textures like no tomorrow.
If you create a texture in a script, you can still run into this problem but in an Editor script it can be much worse. It's not just about eating up memory of your game, it's about eating up memory of Unity, which can get very scary very quickly.
But Textures are just variables right, how are they leaking? You have to remember that Textures and Materials in Unity are not regular variables. They represent assets that could be on the disk, or written to the disk potentially. Not only that but caching them means that the engine can actually render them. Textures and Materials don't get cleaned up until you clean them up. Most of the time this is no problem because normally you'd just load a texture from the disk and apply it to a blank material. If that material already has a texture though, delete it before you apply the new one, or the old one will remain in memory.
No comments:
Post a Comment