分享一下我找到的一篇关于UNity3d做手机游戏对象池应用的文章。

The script is really simple but it has helped the performance in my iOS game tremendously by limiting the number of instantiations that happen at runtime.

这个脚本非常简单,但它可以通过大量减少实例化所带来的开销使我的iOS游戏得到很大的性能提升。

What it does:

The object pool allow you to buffer or pool objects you plan on reusing many time throughout your game, by allowing you to request a new object from it, and tell it whether or not it must give you an object or only give you an object thats available. It also buffers objects at the start to give you a pool to work with initially.

对象池可以缓存你计划在游戏中重复利用的对象,并允许你从中调用,同时它也可以判断是否响应你的调用或者只给你提供可用的对象。它也可以在一开始缓存很多对象来为你提供一个池来进行工作。

How to use:

  1. Add the ObjectPool.cs behavior to a GameObject.
  2. In the object prefabs array set the prefabs you want to be pooled and reused throughout the game.
  3. In the amount to buffer array, specify how many of each object you want to instantiate on the scene start so you have pooled objects to start with. If you don't want to specify each, the default buffer amount will just be used.
  4. In your game call ObjectPool.instance.GetObjectForType(objectType,onlyPooled). For the object type just give the name of the prefab you want to spawn. Specify true or false for the onlyPooled value, if true it will only return a GameObject if there is already an object pooled, if false it will instantiate a new object if one is not available. (Set true if you want to limit how many objects are pooled, very helpful if you want a limited number of effects to ever happen at one time).
  5. Make sure your Gameobject you get from the pool knows when to add itself back into the pool if removed.
  1. 把脚本ObjectPool.cs链接到一个GameObject上。
  2. 在物体预设数组中设置你想要放到池中并重复利用的预设物体。
  3. 在缓冲数组中,指定你希望每个物体在游戏开始时被实例化的数量,这样在开始的时候你就有了池对象。
  4. 在你的游戏中调用ObjectPool.instance.GetObjectForType(objectType,onlyPooled)来使用它。objectType写你想生成的预设的名字、并为onlyPooled指定布尔值,如果返回真,它将返回你已经放到池中的对象;如果返回假,它将实例化一个全新的对象。(如果你想限制被池对象的数量,那么设定为真,这样做非常有用,尤其是在需要限制同时播放特效的数量的时候)。
  5. 确保你从池中调用的对象知道当它被删除时需要返回到池中。

I have also included the Effect.cs and SoundEffect.cs I use in my game to get anyone started right away. The Effect.cs behavior should be added to a game object, then have any number of ParticleEmitters added to it which will run a single emit each time StartEffect is called. Then after a set amount of time it will reset the effect and pool itself. SoundEffect, does a similar thing but with sound effects.

我同时写了Effect.cs和SoundEffect.cs脚本,并把他们用到了游戏中所有需要的地方。Effect.cs脚本需要链接到一个game object上,之后需要加入一些粒子发射器到脚本,当StartEffect被调用时,每次只运行一次发射。然后在过了设定的时间后,它将重置特效并把自己放回池中。SoundEffect的功能和它差不多,只是利用在音效上。

I hope this can help people out who need to limit the number of instantiate calls made with reusable objects.

我希望这个可以帮到有需要的人。


下面的截图我无法转载,所以留下地址:

http://www.liyunpeng.cn/post/2014-08-29/40062790120