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

 

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


推荐阅读
  • Tomcat SSL 配置指南
    本文详细介绍了如何在 Tomcat 中配置 SSL,以确保 Web 应用的安全性。通过正确的配置,可以启用 HTTPS 协议并保护数据传输的安全。 ... [详细]
  • 本文介绍了实时流协议(RTSP)的基本概念、组成部分及其与RTCP的交互过程,详细解析了客户端请求格式、服务器响应格式、常用方法分类及协议流程,并提供了SDP格式的深入解析。 ... [详细]
  • 本文详细介绍了 Java 中 org.w3c.dom.Node 类的 isEqualNode() 方法的功能、参数及返回值,并通过多个实际代码示例来展示其具体应用。此方法用于检测两个节点是否相等,而不仅仅是判断它们是否为同一个对象。 ... [详细]
  • 探讨如何有效应对卡巴斯基密钥被列入黑名单的情况,提供安全可靠的解决方案,确保用户能够继续使用卡巴斯基的全部功能。 ... [详细]
  • 本文详细介绍如何在华为鲲鹏平台上构建和使用适配ARM架构的Redis Docker镜像,解决常见错误并提供优化建议。 ... [详细]
  • 本文详细介绍了Java中HashSet的工作原理及其源码分析。HashSet实现了Set接口,内部通过HashMap来存储数据,不保证元素的迭代顺序,且允许null值的存在。文章不仅涵盖了HashSet的基本概念,还深入探讨了其内部实现细节。 ... [详细]
  • Python Requests模块中的身份验证机制
    随着Web服务的发展,身份验证成为了确保数据安全的重要环节。本文将详细介绍如何利用Python的Requests库实现不同类型的HTTP身份验证,包括基本身份验证、摘要式身份验证以及OAuth 1认证等。 ... [详细]
  • 探讨了在VB中使用WebBrowser控件时遇到的‘无法找到或打开C:\WINDOWS\system32\ieframe.dll’问题,并提供了解决方案。 ... [详细]
  • 通过网上的资料我自己的实际内核编译,我把对Linux内核编译的过程写在这里,也许对其他的Linux爱好者的编译学习有些帮助,其中很大部分是 ... [详细]
  • 在 Ubuntu 22.04 LTS 上部署 Jira 敏捷项目管理工具
    Jira 敏捷项目管理工具专为软件开发团队设计,旨在以高效、有序的方式管理项目、问题和任务。该工具提供了灵活且可定制的工作流程,能够根据项目需求进行调整。本文将详细介绍如何在 Ubuntu 22.04 LTS 上安装和配置 Jira。 ... [详细]
  • 如题:2017年10月分析:还记得在没有智能手机的年代大概就是12年前吧,手机上都会有WAP浏览器。当时没接触网络原理,也不 ... [详细]
  • 在Ubuntu 18.04上使用Nginx搭建RTMP流媒体服务器
    本文详细介绍了如何在Ubuntu 18.04上使用Nginx和nginx-rtmp-module模块搭建RTMP流媒体服务器,包括环境搭建、配置文件修改和推流拉流操作。适用于需要搭建流媒体服务器的技术人员。 ... [详细]
  • 本文探讨了使用 JavaScript 和 HTML5 Canvas 实现经典马里奥游戏克隆过程中遇到的碰撞检测和跳跃问题,并提供了详细的解决方案。 ... [详细]
  • Flutter 核心技术与混合开发模式深入解析
    本文深入探讨了 Flutter 的核心技术,特别是其混合开发模式,包括统一管理模式和三端分离模式,以及混合栈原理。通过对比不同模式的优缺点,帮助开发者选择最适合项目的混合开发策略。 ... [详细]
  • Spring Boot使用AJAX从数据库读取数据异步刷新前端表格
      近期项目需要是实现一个通过筛选选取所需数据刷新表格的功能,因为表格只占页面的一小部分,不希望整个也页面都随之刷新,所以首先想到了使用AJAX来实现。  以下介绍解决方法(请忽视 ... [详细]
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社区 版权所有