热门标签 | HotTags
当前位置:  开发笔记 > 后端 > 正文

和Keyle一起学PoolManager

请先下载PoolManager网上有很多资源我就不列举了。这是官网http:support.path-o-logical.com先看ExampleSceneCrea

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

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

 

先看Example Scene

image

 

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

using UnityEngine; using System.Collections; using System.Collections.Generic; /// 
/// An example that shows the creation of a pool. ///
public class CreationExample : MonoBehaviour { public Transform testPrefab; public string poolName = "Creator"; public int spawnAmount = 10; public float spawnInterval = 0.25f; private SpawnPool pool; ///
/// 设置预制池不同的属性 ///

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)"; } ///
/// 周期性生产实例 ///

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; ///
/// 周期性回收实例 ///

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 ,写相应的初始化代码。

/// 
/// 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 ///

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

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

 /// 
/// 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. ///
///
/// 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 ///
/// The position to set the instance to
/// The rotation to set the instance to
///
/// 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. ///

 

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

/// 
/// 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. ///

 

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

 

//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 则是每次循环销毁的数量 )。

/// 
/// The number of instances to preload ///

public int preloadAmount = 1; ///
/// Displays the 'preload over time' options ///

public bool preloadTime = false; ///
/// The number of frames it will take to preload all requested instances ///

public int preloadFrames = 2; ///
/// The number of seconds to wait before preloading any instances ///

public float preloadDelay = 0; ///
/// 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. ///

public bool limitInstances = false; ///
/// This is the max number of instances allowed if 'limitInstances' is ON. ///

public int limitAmount = 100; ///
/// 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. ///

public bool limitFIFO = false; // Keep after limitAmount for auto-inspector

///
/// 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. ///

public bool cullDespawned = false; ///
/// The number of TOTAL (spawned + despawned) instances to keep. ///

public int cullAbove = 50; ///
/// 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'. ///

public int cullDelay = 60; ///
/// The maximum number of instances to destroy per this.cullDelay ///

public int cullMaxPerPass = 5;

 

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

 

/// 
/// 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). ///

///
/// The name for the new SpawnPool. The GameObject will have the word "Pool" /// Added at the end. ///
/// A reference to the new SpawnPool component
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(); } ///
///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. ///

///
/// The name for the new SpawnPool. The GameObject will have the word "Pool" /// Added at the end. ///
/// A GameObject to add the SpawnPool Component
/// A reference to the new SpawnPool component
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(); } finally { // Runs no matter what
owner.gameObject.name = ownerName; } }

 

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


推荐阅读
  • 采用IKE方式建立IPsec安全隧道
    一、【组网和实验环境】按如上的接口ip先作配置,再作ipsec的相关配置,配置文本见文章最后本文实验采用的交换机是H3C模拟器,下载地址如 ... [详细]
  • 本文介绍如何在华为CE交换机上配置M-LAG(多链路聚合组),以实现CE1和CE2设备作为VLAN 10网关的高可用性。通过详细的配置步骤,确保网络冗余和稳定性。 ... [详细]
  • 深入解析Redis内存对象模型
    本文详细介绍了Redis内存对象模型的关键知识点,包括内存统计、内存分配、数据存储细节及优化策略。通过实际案例和专业分析,帮助读者全面理解Redis内存管理机制。 ... [详细]
  • 本文详细介绍了C++中map容器的多种删除和交换操作,包括clear、erase、swap、extract和merge方法,并提供了完整的代码示例。 ... [详细]
  • 本文详细介绍了在腾讯云服务器上配置 phpMyAdmin 的方法,包括安装、配置和解决常见问题。通过这些步骤,您可以轻松地在腾讯云环境中部署并使用 phpMyAdmin。 ... [详细]
  • 目录一、salt-job管理#job存放数据目录#缓存时间设置#Others二、returns模块配置job数据入库#配置returns返回值信息#mysql安全设置#创建模块相关 ... [详细]
  • 本文介绍如何在Spring Boot项目中集成Redis,并通过具体案例展示其配置和使用方法。包括添加依赖、配置连接信息、自定义序列化方式以及实现仓储接口。 ... [详细]
  • Coursera ML 机器学习
    2019独角兽企业重金招聘Python工程师标准线性回归算法计算过程CostFunction梯度下降算法多变量回归![选择特征](https:static.oschina.n ... [详细]
  • 本文介绍如何使用 Angular 6 的 HttpClient 模块来获取 HTTP 响应头,包括代码示例和常见问题的解决方案。 ... [详细]
  • 全面解析运维监控:白盒与黑盒监控及四大黄金指标
    本文深入探讨了白盒和黑盒监控的概念,以及它们在系统监控中的应用。通过详细分析基础监控和业务监控的不同采集方法,结合四个黄金指标的解读,帮助读者更好地理解和实施有效的监控策略。 ... [详细]
  • 实用正则表达式有哪些
    小编给大家分享一下实用正则表达式有哪些,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下 ... [详细]
  • 主板IO用W83627THG,用VC如何取得CPU温度,系统温度,CPU风扇转速,VBat的电压. ... [详细]
  • 本文介绍了如何使用JavaScript的Fetch API与Express服务器进行交互,涵盖了GET、POST、PUT和DELETE请求的实现,并展示了如何处理JSON响应。 ... [详细]
  • 配置多VLAN环境下的透明SQUID代理
    本文介绍如何在包含多个VLAN的网络环境中配置SQUID作为透明网关。网络拓扑包括Cisco 3750交换机、PANABIT防火墙和SQUID服务器,所有设备均部署在ESXi虚拟化平台上。 ... [详细]
  • Windows 7 64位系统下Redis的安装与PHP Redis扩展配置
    本文详细介绍了在Windows 7 64位操作系统中安装Redis以及配置PHP Redis扩展的方法,包括下载、安装和基本使用步骤。适合对Redis和PHP集成感兴趣的开发人员参考。 ... [详细]
author-avatar
拍友2602921297
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有