热门标签 | 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; } }

 

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


推荐阅读
  • 在Kubernetes上部署JupyterHub的步骤和实验依赖
    本文介绍了在Kubernetes上部署JupyterHub的步骤和实验所需的依赖,包括安装Docker和K8s,使用kubeadm进行安装,以及更新下载的镜像等。 ... [详细]
  • 如何自行分析定位SAP BSP错误
    The“BSPtag”Imentionedintheblogtitlemeansforexamplethetagchtmlb:configCelleratorbelowwhichi ... [详细]
  • 基于PgpoolII的PostgreSQL集群安装与配置教程
    本文介绍了基于PgpoolII的PostgreSQL集群的安装与配置教程。Pgpool-II是一个位于PostgreSQL服务器和PostgreSQL数据库客户端之间的中间件,提供了连接池、复制、负载均衡、缓存、看门狗、限制链接等功能,可以用于搭建高可用的PostgreSQL集群。文章详细介绍了通过yum安装Pgpool-II的步骤,并提供了相关的官方参考地址。 ... [详细]
  • Monkey《大话移动——Android与iOS应用测试指南》的预购信息发布啦!
    Monkey《大话移动——Android与iOS应用测试指南》的预购信息已经发布,可以在京东和当当网进行预购。感谢几位大牛给出的书评,并呼吁大家的支持。明天京东的链接也将发布。 ... [详细]
  • Nginx使用(server参数配置)
    本文介绍了Nginx的使用,重点讲解了server参数配置,包括端口号、主机名、根目录等内容。同时,还介绍了Nginx的反向代理功能。 ... [详细]
  • 云原生边缘计算之KubeEdge简介及功能特点
    本文介绍了云原生边缘计算中的KubeEdge系统,该系统是一个开源系统,用于将容器化应用程序编排功能扩展到Edge的主机。它基于Kubernetes构建,并为网络应用程序提供基础架构支持。同时,KubeEdge具有离线模式、基于Kubernetes的节点、群集、应用程序和设备管理、资源优化等特点。此外,KubeEdge还支持跨平台工作,在私有、公共和混合云中都可以运行。同时,KubeEdge还提供数据管理和数据分析管道引擎的支持。最后,本文还介绍了KubeEdge系统生成证书的方法。 ... [详细]
  • 如何去除Win7快捷方式的箭头
    本文介绍了如何去除Win7快捷方式的箭头的方法,通过生成一个透明的ico图标并将其命名为Empty.ico,将图标复制到windows目录下,并导入注册表,即可去除箭头。这样做可以改善默认快捷方式的外观,提升桌面整洁度。 ... [详细]
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • 本文详细介绍了PHP中与URL处理相关的三个函数:http_build_query、parse_str和查询字符串的解析。通过示例和语法说明,讲解了这些函数的使用方法和作用,帮助读者更好地理解和应用。 ... [详细]
  • Metasploit攻击渗透实践
    本文介绍了Metasploit攻击渗透实践的内容和要求,包括主动攻击、针对浏览器和客户端的攻击,以及成功应用辅助模块的实践过程。其中涉及使用Hydra在不知道密码的情况下攻击metsploit2靶机获取密码,以及攻击浏览器中的tomcat服务的具体步骤。同时还讲解了爆破密码的方法和设置攻击目标主机的相关参数。 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • 本文主要对比了Proxy和Object.defineProperty两种对象属性操作方式的优劣,并介绍了它们各自的应用场景。Proxy具有直接监听对象和数组变化、多种拦截方法以及新标准的性能优势等特点,而Object.defineProperty则兼容性好,支持IE9,并且无法用polyfill磨平浏览器兼容性问题。根据具体需求和浏览器兼容性考虑,选择合适的方式进行对象属性操作。 ... [详细]
  • 本文介绍了Python高级网络编程及TCP/IP协议簇的OSI七层模型。首先简单介绍了七层模型的各层及其封装解封装过程。然后讨论了程序开发中涉及到的网络通信内容,主要包括TCP协议、UDP协议和IPV4协议。最后还介绍了socket编程、聊天socket实现、远程执行命令、上传文件、socketserver及其源码分析等相关内容。 ... [详细]
  • Oracle Database 10g许可授予信息及高级功能详解
    本文介绍了Oracle Database 10g许可授予信息及其中的高级功能,包括数据库优化数据包、SQL访问指导、SQL优化指导、SQL优化集和重组对象。同时提供了详细说明,指导用户在Oracle Database 10g中如何使用这些功能。 ... [详细]
  • Windows下配置PHP5.6的方法及注意事项
    本文介绍了在Windows系统下配置PHP5.6的步骤及注意事项,包括下载PHP5.6、解压并配置IIS、添加模块映射、测试等。同时提供了一些常见问题的解决方法,如下载缺失的msvcr110.dll文件等。通过本文的指导,读者可以轻松地在Windows系统下配置PHP5.6,并解决一些常见的配置问题。 ... [详细]
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社区 版权所有