Advertisement
LittleAngel

Pooling

Jul 2nd, 2012
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. Pooling. There are some tools for this on Asset Store, but in general, pooling goes like this:
  2.  
  3. [code]
  4. private List<GameObject> objectPool;
  5.  
  6. objectPool = new List <GameObject>();
  7.  
  8. // optionally one can instantiate any number of object in Awake()
  9.  
  10. if (Input.GetButton ("Fire1") && canFire) {
  11. GameObject myObject = GetObject ();
  12. DoSomethingWith (myObject);
  13. }
  14.  
  15. void GetObject () {
  16. foreach (GameObject thisObject in objectPool) {
  17. if (thisObject.gameObject.active = false) {
  18. thisObject.SetActiveRecursively (true);
  19. return thisObject;
  20. }
  21. }
  22. GameObject newObject = (GameObject)Instantiate (objectPrefab, poolSpawnPoint.position, Quaternion.identity);
  23. newObject.transform.parent = poolSpawnPoint; // for organizational purposes only
  24. objectPool.Add (newObject);
  25. return newObject;
  26. }
  27. [/code]
  28.  
  29. You create a list of objects that you pool. When you want an object, you check the object pool for an inactive object. If there is no inactive object in the pool, then you create a new object and add it to the pool. When you are done with the object, don't destroy, simply set it to inactive. Optionally (and it's probably a good idea) just after initializing the pool list in awake, one could go through an arbitrary number of iterations and instantiate & add items to the pool - 5, 10, 50, 100 depending on how many you think you might need. When making the shots in the video, both the laser bolts and torpedoes are pooled, so I reuse them all the time. This prevents excessive use of the garbage collector removing destroyed objects.
  30.  
  31. Where I run into trouble is that I am also pooling the explosion prefabs, and I was setting an instance of the explosion prefab to follow the asteroids and as they were being destroyed, it was screwing up my references by destroying the explosion prefabs along with them which were being tracked by the pool.
  32.  
  33. In general, instantiate/destroy is simple and the pattern supplied by Unity as the "typical" solution. Coming from Unity mobile gaming, I love pools, and I am so used to them, I don't see any real overhead in using them over instantiate/destroy.
  34.  
  35. Your static cache seems to be doing some of this work as well - preinstantiating the prefabs.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement