- Home /
Instantiate prefabs to save memory
Hey guys!
I have a 3D world and in that world I want to instantiate people based on the player's location or something similar. I don't want to load all people at once, as that will put load on memory. I've seen that many popular games also do this. I just need guidance on how to accomplish this. I have wayPoints set throughout the game as pathways for people to walk on.
I was thinking maybe create a certain number of people around the player's radius and put them on the random wayPoints inside the radius, then delete people if they are outside the radius. Is this good, or is there a better way? I eventually want this on mobile phones, so performance is a must.
Update: What if I leave all these people in the scene, what kind of performance hit should i expect? They all have scripts, colliders, meshes, etc. They're just walking around, not doing much. But they are large in number, around 500.
Many Thanks!
Answer by Kryptos · Aug 31, 2012 at 08:09 AM
Don't destroy people this is bad ;)
Joking aside, don't use Destoy/Instantiate because this is bad for memory (and performance). You can create a pool of objects. When a object goes outside the player radius, just teleport it to the other side so that it can enter the radius again.
And to improve performance, try to share as much data as possible between all objects : same material, same texture (use texture atlases), same mesh (and low-poly mesh so that dynamic batching can work).
Yeh, I plan to have only about 4 types of people, aside from the main characters....I like your idea...I should instantiate about 50 people and move them if they are outside the radius, using a trigger...I like that
Answer by landon912 · Aug 31, 2012 at 03:45 AM
You could use occlusion culling to save memory instead of deleting people. If this is not enough then I would just use a big sphere trigger and save the people's current location then destroy them if outside of circle. That way you can spawn them in the exact same spot when you come back
occlusion culling is Unity Pro, but I'm using the free version
So, on the second one, I would store their position and rotation before destroying them and create them again on TriggerEnter? I'm a bit confused, but I want to give it a try...
Yes look at playerprefs in the script reference and you can store there data in that.