I’m making a game that will have a lot of copies of textured objects in a scene at once, instantiated from a couple of core prefabs. The geometry and lighting are simple enough that I’m not worried about a graphical bottleneck, but I am worried about loading all of those textures into memory. If I have a “tree” prefab for instance, and I instantiate 500 of it into a scene, is Unity going to load 500 copies of the tree texture into memory? Or is it going to load 500 objects that reference the same single tree texture? It feels like it might be the latter because I can change the prefab and all copies in the scene will change. But on the other hand, it’s clearly a deep copy because I can change the properties of individual copies without affecting all of them, which then feels like 500 copies of the texture.
More concisely: Do I need to make a texture library that copied objects reference to get their texture to accomplish a Flyweight pattern, or are prefabs good enough?
Unity handles it, check memory profiler and wipe your brow. Serialization is still heavy though, for the prefabs themselves.
1 Like
Phew! That’s good news. I knew I could always profile my build but I wasn’t sure if I could read the output and know definitively if one or the other thing is happening.
I’ve heard the word “serialization” used a lot. In my mind that means writing runtime data to disk to have a persistent state outside the lifetime of the program session. But in the context of Unity people seem to be using it slightly differently, and I’ve never really understood it fully. Are you using it in the sense that it would be heavy to write all this data to disk? What if I developed my own serialization technique that uses very lightweight values to represent state within these prefabs?
It’s writing on the Unity editor side but prefabs and scenes aren’t really efficiently stored, so if you’re using 500 tree prefabs that are complex, there will be additional data baggage vs using an DrawMeshInstancedIndirect shader to render 500 tree meshes.
Basically just tool for the job: use instancing for vegetation and prefabs for complex structures that you don’t have many of. This would change in DOTS in future but not now.
Might be overreacting though, it could be your scenario is not heavy, check profiler anyway. Note: prefabs don’t really exist in a built scene, they’re unpacked, but it’s still more memory than if you just render a whole batch. Not duplicate asset (texture etc) memory though so you’re fine there!
1 Like