和Keyle一起学 PoolManager

请先下载 PoolManager 网上有很多资源我就不列举了 。

这是官网 http://support.path-o-logical.com

 

先看Example Scene

image

 

CreationExample 脚本 ,请优先阅读以下代码与注释以便快速了解PoolManager插件 。

using UnityEngine; using System.Collections; using System.Collections.Generic; /// <description>
/// An example that shows the creation of a pool. /// </description>
public class CreationExample : MonoBehaviour {     public Transform testPrefab; public string poolName = "Creator"; public int spawnAmount = 10; public float spawnInterval = 0.25f; private SpawnPool pool; /// <summary>
    /// 设置预制池不同的属性 /// </summary>
    private void Start() { this.pool = PoolManager.Pools.Create(this.poolName); // 将这个池作为当前物体的子物体
        this.pool.group.parent = this.transform; // 设置池的位置 角度
        this.pool.group.localPosition = new Vector3(1.5f, 0, 0); this.pool.group.localRotation = Quaternion.identity; //PoolManager创建一个预制池,这个池不需要你预先装载,如果没有特殊需求跳过下面步骤,不必要填写下面的参数,预制池自动采取默认参数。
        PrefabPool prefabPool = new PrefabPool(testPrefab); prefabPool.preloadAmount = 5;//默认初始化就是自动生成五个实例
        prefabPool.cullDespawned = true; prefabPool.cullAbove = 10; prefabPool.cullDelay = 1; prefabPool.limitInstances = true; prefabPool.limitAmount = 5; prefabPool.limitFIFO = true; this.pool.CreatePrefabPool(prefabPool);//PoolManager在池组中创建一个预制池

        this.StartCoroutine(Spawner());//开始生产 // 我们有两种方式拿到池中的预制 // 在Shapes池中,我们有一个Key(name)为Cube的预制 // 用名称 或者 Transform 获取都可以 // 值得注意的是 通过Key获取的 会作用于这个池中的所有预制 // 通过Transform获取的,只作用于唯一的一个预制
        Transform cubePrefab = PoolManager.Pools["test"].prefabs["Cube"]; Transform cubeinstance = PoolManager.Pools["Shapes"].Spawn(cubePrefab); cubeinstance.name = "Cube (Spawned By CreationExample.cs)"; } /// <summary>
    /// 周期性生产实例 /// </summary>
    private IEnumerator Spawner() { int count = this.spawnAmount; Transform inst; Transform test = PoolManager.Pools[poolName].prefabs["Sphere"];//在这个池中拿到需要生成的预制;

        while (count > 0) { inst = this.pool.Spawn(testPrefab, Vector3.zero, Quaternion.identity);//从池组中取得预制
 inst.localPosition = new Vector3(this.spawnAmount - count, 0, 0); if (count == 5) { inst.renderer.material.color = Color.red; t = inst; } count--; yield return new WaitForSeconds(this.spawnInterval); } this.StartCoroutine(Despawner());//生产速度
 } Transform t; /// <summary>
    /// 周期性回收实例 /// </summary>
    private IEnumerator Despawner() { while (this.pool.Count > 0) { Transform instance = this.pool[pool.Count - 1]; this.pool.Despawn(instance);  // PoolManager回收 但是没有彻底还原预制原始状态 需要自己控制详情看下面的文档说明
            yield return new WaitForSeconds(this.spawnInterval);//回收速度
 } } }

 

附上一段提纲文档说明 ,简而言之插件给我们提供了 一个保持原始状态的途径,在预设的GameObject添加 OnDespawned 和 OnRespawned ,写相应的初始化代码。

/// <description>
/// Online Docs: ///     http://docs.poolmanager2.path-o-logical.com/code-reference/spawnpool
///
/// A special List class that manages object pools and keeps the scene /// organized. ///
/// * Only active/spawned instances are iterable. Inactive/despawned /// instances in the pool are kept internally only. ///
/// * Instanciated objects can optionally be made a child of this GameObject /// (reffered to as a 'group') to keep the scene hierachy organized. ///
/// * Instances will get a number appended to the end of their name. E.g. /// an "Enemy" prefab will be called "Enemy(Clone)001", "Enemy(Clone)002", /// "Enemy(Clone)003", etc. Unity names all clones the same which can be /// confusing to work with. ///
/// * Objects aren't destroyed by the Despawn() method. Instead, they are /// deactivated and stored to an internal queue to be used again. This /// avoids the time it takes unity to destroy gameobjects and helps /// performance by reusing GameObjects. ///
/// * Two events are implimented to enable objects to handle their own reset needs. /// Both are optional. /// 1) When objects are Despawned BroadcastMessage("OnDespawned()") is sent. /// 2) When reactivated, a BroadcastMessage("OnRespawned()") is sent. /// This /// </description>

Spawns 功能说明文档上也有明确的描述 ,在实例化预设时不会调Awake(),而是通过广播道GameObject的 OnSpawned 方法,初始化的时候不要弄错了。

Broadcasts "OnSpawned" to the instance. Use this instead of Awake()

 /// <description>
    /// Spawns an instance or creates a new instance if none are available. /// Either way, an instance will be set to the passed position and /// rotation. ///
    /// Detailed Information: /// Checks the Data structure for an instance that was already created /// using the prefab. If the prefab has been used before, such as by /// setting it in the Unity Editor to preload instances, or just used /// before via this function, one of its instances will be used if one /// is available, or a new one will be created. ///
    /// If the prefab has never been used a new PrefabPool will be started /// with default options. ///
    /// To alter the options on a prefab pool, use the Unity Editor or see /// the documentation for the PrefabPool class and /// SpawnPool.SpawnPrefabPool() ///
    /// Broadcasts "OnSpawned" to the instance. Use this instead of Awake() ///
    /// This function has the same initial signature as Unity's Instantiate() /// that takes position and rotation. The return Type is different though. /// </description>
    /// <param name="prefab">
    /// The prefab used to spawn an instance. Only used for reference if an /// instance is already in the pool and available for respawn. /// NOTE: Type = Transform /// </param>
    /// <param name="pos">The position to set the instance to</param>
    /// <param name="rot">The rotation to set the instance to</param>
    /// <returns>
    /// The instance's Transform. ///
    /// If the Limit option was used for the PrefabPool associated with the /// passed prefab, then this method will return null if the limit is /// reached. You DO NOT need to test for null return values unless you /// used the limit option. /// </returns>

 

PrefabPool的功能文档上写到 这个插件的池技术的核心还是在于 PrefabPool ,以后我会再出一篇博文专门讲述PrefabPool。

/// <summary>
/// This class is used to display a more complex user entry interface in the /// Unity Editor so we can collect more options related to each Prefab. ///
/// See this class documentation for Editor Options. ///
/// This class is also the primary pool functionality for SpawnPool. SpawnPool /// manages the Pool using these settings and methods. See the SpawnPool /// documentation for user documentation and usage. /// </summary>

 

该看的文档到此结束,最后分别叙述下 池的默认选项,这段代码是一开头我给出的

 

//PoolManager创建一个预制池,这个池不需要你预先装载,如果没有特殊需求跳过下面步骤,不必要填写下面的参数,预制池自动采取默认参数。
 PrefabPool prefabPool = new PrefabPool(testPrefab); prefabPool.preloadAmount = 5;//PoolManager默认初始化就是自动生成五个实例
         prefabPool.cullDespawned = true; prefabPool.cullAbove = 10; prefabPool.cullDelay = 1; prefabPool.limitInstances = true; prefabPool.limitAmount = 5; prefabPool.limitFIFO = true; this.pool.CreatePrefabPool(prefabPool);//PoolManager在池组中创建一个预制池

 

 

又扒了一段代码,相信这些你们能懂的,我就不一个一个说了。有些东西还是值得一看的,比如 limitFIFO ,先入先出的概念,开启后继续Spwan()出来的预设会换掉最开始出来的预设(重新回收)。

再看这个 cullDespawned 选项 ,作者说:“这只在极端情况下使用,没事儿别开这个选项除非你想自己管理内存 !”,咱们既然使用这个插件当然是想让其托管减小内存的开销,所以默认false吧。

顺带一说 cullAbove , 在池中生产超过定量数值的预设部分将会被销毁(cullDelay 用于设置销毁的延迟时间循环 而cullMaxPerPass 则是每次循环销毁的数量 )。

/// <summary>
    /// The number of instances to preload /// </summary>
    public int preloadAmount = 1; /// <summary>
    /// Displays the 'preload over time' options /// </summary>
    public bool preloadTime = false; /// <summary>
    /// The number of frames it will take to preload all requested instances /// </summary>
    public int preloadFrames = 2; /// <summary>
    /// The number of seconds to wait before preloading any instances /// </summary>
    public float preloadDelay = 0; /// <summary>
    /// Limits the number of instances allowed in the game. Turning this ON /// means when 'Limit Amount' is hit, no more instances will be created. /// CALLS TO SpawnPool.Spawn() WILL BE IGNORED, and return null! ///
    /// This can be good for non-critical objects like bullets or explosion /// Flares. You would never want to use this for enemies unless it makes /// sense to begin ignoring enemy spawns in the context of your game. /// </summary>
    public bool limitInstances = false; /// <summary>
    /// This is the max number of instances allowed if 'limitInstances' is ON. /// </summary>
    public int limitAmount = 100; /// <summary>
    /// FIFO stands for "first-in-first-out". Normally, limiting instances will /// stop spawning and return null. If this is turned on (set to true) the /// first spawned instance will be despawned and reused instead, keeping the /// total spawned instances limited but still spawning new instances. /// </summary>
    public bool limitFIFO = false;  // Keep after limitAmount for auto-inspector
    
    /// <summary>
    /// Turn this ON to activate the culling feature for this Pool. /// Use this feature to remove despawned (inactive) instances from the pool /// if the size of the pool grows too large. ///
    /// DO NOT USE THIS UNLESS YOU NEED TO MANAGE MEMORY ISSUES! /// This should only be used in extreme cases for memory management. /// For most pools (or games for that matter), it is better to leave this /// off as memory is more plentiful than performance. If you do need this /// you can fine tune how often this is triggered to target extreme events. ///
    /// A good example of when to use this would be if you you are Pooling /// projectiles and usually never need more than 10 at a time, but then /// there is a big one-off fire-fight where 50 projectiles are needed. /// Rather than keep the extra 40 around in memory from then on, set the /// 'Cull Above' property to 15 (well above the expected max) and the Pool /// will Destroy() the extra instances from the game to free up the memory. ///
    /// This won't be done immediately, because you wouldn't want this culling /// feature to be fighting the Pool and causing extra Instantiate() and /// Destroy() calls while the fire-fight is still going on. See /// "Cull Delay" for more information about how to fine tune this. /// </summary>
    public bool cullDespawned = false; /// <summary>
    /// The number of TOTAL (spawned + despawned) instances to keep. /// </summary>
    public int cullAbove = 50; /// <summary>
    /// The amount of time, in seconds, to wait before culling. This is timed /// from the moment when the Queue's TOTAL count (spawned + despawned) /// becomes greater than 'Cull Above'. Once triggered, the timer is repeated /// until the count falls below 'Cull Above'. /// </summary>
    public int cullDelay = 60; /// <summary>
    /// The maximum number of instances to destroy per this.cullDelay /// </summary>
    public int cullMaxPerPass = 5;

 

喔,好像还漏了点什么 比如 动态创建一个 “池”,而不是实现做成预制 。在 SpawnPoolsDict 类中提供了那么一个方法 。

 

/// <summary>
    /// Creates a new GameObject with a SpawnPool Component which registers itself /// with the PoolManager.Pools dictionary. The SpawnPool can then be accessed /// directly via the return value of this function or by via the PoolManager.Pools /// dictionary using a 'key' (string : the name of the pool, SpawnPool.poolName). /// </summary>
    /// <param name="poolName">
    /// The name for the new SpawnPool. The GameObject will have the word "Pool" /// Added at the end. /// </param>
    /// <returns>A reference to the new SpawnPool component</returns>
    public SpawnPool Create(string poolName) { // Add "Pool" to the end of the poolName to make a more user-friendly // GameObject name. This gets stripped back out in SpawnPool Awake()
        var owner = new GameObject(poolName + "Pool"); return owner.AddComponent<SpawnPool>(); } /// <summary>
    ///Creates a SpawnPool Component on an 'owner' GameObject which registers /// itself with the PoolManager.Pools dictionary. The SpawnPool can then be /// accessed directly via the return value of this function or via the /// PoolManager.Pools dictionary. /// </summary>
    /// <param name="poolName">
    /// The name for the new SpawnPool. The GameObject will have the word "Pool" /// Added at the end. /// </param>
    /// <param name="owner">A GameObject to add the SpawnPool Component</param>
    /// <returns>A reference to the new SpawnPool component</returns>
    public SpawnPool Create(string poolName, GameObject owner) { if (!this.assertValidPoolName(poolName)) return null; // When the SpawnPool is created below, there is no way to set the poolName // before awake runs. The SpawnPool will use the gameObject name by default // so a try statement is used to temporarily change the parent's name in a // safe way. The finally block will always run, even if there is an error.
        string ownerName = owner.gameObject.name; try { owner.gameObject.name = poolName; // Note: This will use SpawnPool.Awake() to finish init and self-add the pool
            return owner.AddComponent<SpawnPool>(); } finally { // Runs no matter what
            owner.gameObject.name = ownerName; } }

 

最后小结一下,首先这篇文章我看也算不得教程,更像是笔记整理,今天刚开始看便只写了写便于快速上手的摘记 。以后会继续写关于这方面的

posted @ 2014-07-12 22:10  keyle_xiao  阅读(2350)  评论(0编辑  收藏  举报