山寨小小军团开发笔记 之 GamePool
很多时候我们对于物体(比如弓箭)大量的生成与销毁,这个时候可以把弓箭放在内存池中进行管理,加快体验。自己Copy了一个简易版的。
一、代码
GameObjectPoolManager.cs
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text; // A general pool object for reusable game objects.
//
// It supports spawning and unspawning game objects that are
// instantiated from a common prefab. Can be used preallocate
// objects to avoid calls to Instantiate during gameplay. Can
// also create objects on demand (which it does if no objects
// are available in the pool).
public class GameObjectPoolManager { public GameObject parent; // The prefab that the game objects will be instantiated from.
private GameObject prefab;
// The list of available game objects (initially empty by default).
private Stack<GameObject> available; // The list of all game objects created thus far (used for efficiently
// unspawning all of them at once, see UnspawnAll).
private List<GameObject> all; // An optional function that will be called whenever a new object is instantiated.
// The newly instantiated object is passed to it, which allows users of the pool
// to do custom initialization.
private Callback<GameObject> initializeFunction; private Callback<GameObject> destroyFunction; //// Indicates whether the pool's game objects should be activated/deactivated
//// recursively (i.e. the game object and all its children) or non-recursively (just the
//// game object).
//private var setActiveRecursively : boolean; // Creates a pool.
// The initialCapacity is used to initialize the .NET collections, and determines
// how much space they pre-allocate behind the scenes. It does not pre-populate the
// collection with game objects. For that, see the PrePopulate function.
// If an initialCapacity that is <= to zero is provided, the pool uses the default
// initial capacities of its internal .NET collections.
public GameObjectPoolManager(GameObject prefab, Callback<GameObject> initializeFunction, Callback<GameObject> destroyFunction)
{
this.prefab = prefab; this.parent = new GameObject(prefab.name + "Pool"); this.available = new Stack<GameObject>();
this.all = new List<GameObject>(); this.initializeFunction = initializeFunction;
this.destroyFunction = destroyFunction;
} // Spawn a game object with the specified position/rotation.
public GameObject Spawn(Vector3 position, Quaternion rotation)
{
GameObject result = null; if (available.Count == 0)
{
// Create an object and initialize it.
result = GameObject.Instantiate(prefab, position, rotation) as GameObject;
result.transform.parent = parent.transform; // Keep track of it.
all.Add(result);
}
else
{
result = available.Pop() as GameObject; // Get the result's transform and reuse for efficiency.
//Calling gameObject.transform is expensive.
var resultTrans = result.transform;
resultTrans.position = position;
resultTrans.rotation = rotation; result.SetActive(true);
} if (initializeFunction != null) initializeFunction(result); return result;
} // Unspawn the provided game object.
// The function is idempotent. Calling it more than once for the same game object is
// safe, since it first checks to see if the provided object is already unspawned.
// Returns true if the unspawn succeeded, false if the object was already unspawned.
public bool Unspawn(GameObject obj)
{ if (!available.Contains(obj))
{
// Make sure we don't insert it twice.
available.Push(obj);
obj.SetActive(false); if (destroyFunction != null) destroyFunction(obj); return true; // Object inserted back in stack.
}
return false; // Object already in stack.
} // Pre-populates the pool with the provided number of game objects.
void PrePopulate(int count){
GameObject[] array = new GameObject[count];
for(var i = 0; i < count; i++){
array[i] = Spawn(Vector3.zero, Quaternion.identity);
//this.SetActive(array[i], false);
}
for(var j = 0; j < count; j++){
Unspawn(array[j]);
}
}
// Unspawns all the game objects created by the pool.
void UnspawnAll()
{
foreach (var item in available)
{
Unspawn(item);
}
}
// Returns the number of active objects.
int GetActiveCount()
{
return all.Count - available.Count;
} // Returns the number of available objects.
int GetAvailableCount(){
return available.Count;
}
}
二、应用
还是用之前的BezierTest.cs的例子
void Start()
{
arrowPool = new GameObjectPoolManager(arrowPrefab, null, null); //controlPoints = ControlPoints(transform, right);
}
#endregion void Test(bool fireRight)
{
Transform end = fireRight ? right : left; ///在中心点生成弓箭
GameObject curArrow = arrowPool.Spawn(transform.position, Quaternion.Euler(Vector3.zero)); ///计算LookTarget的点 与 贝塞尔曲线的第三个控制点
Vector3[] points = Re_LookTarget_MiddlePerpendicularPoint(curArrow.transform, end); ///初始化发射
ArrowControl arrowControl = curArrow.GetComponent<ArrowControl>();
arrowControl.Init(
points[0],
points[1],
end.position,
3.0f,
delegate()
{
arrowPool.Unspawn(curArrow);
});
}
山寨小小军团开发笔记 之 GamePool的更多相关文章
- 山寨小小军团开发笔记 之 Arrow Projectile
好久没怎么更新博客了,今天抽空来一篇,讨论一下弓箭的轨迹生成. 一.原理 弓箭的轨迹本质就是一个数学问题,使用一个 bezier 曲线公式就可以插值生成.得到轨迹后,做一个lookAt就可以了. 二. ...
- [开发笔记]-未找到与约束ContractName Microsoft.VisualStudio.Text.ITextDocumentFactoryService...匹配的导出【转载自:酷小孩】
原文地址:http://www.cnblogs.com/babycool/p/3199158.html 今天打算用VisualStudio2012做一个js效果页面测试的时候,打开VS2012新建项目 ...
- EasyUI 开发笔记(二)
接上篇 :EasyUI 开发笔记(一) (http://www.cnblogs.com/yiayi/p/3485258.html) 这期就简单介绍下, easyui 的 list 展示, 在easy ...
- EasyUI 开发笔记(一)
由于某些原因,在公司做的后台需要改成类似于Ext.js 形式的后台,主要看好其中的 框架布局,以及tab开页面和弹出式内部窗体. 后来看看,改成EasyUI,较Ext.js 库小很多,也便于公司的初级 ...
- [Openwrt 项目开发笔记]:Openwrt平台搭建(一)
[Openwrt项目开发笔记]系列文章传送门:http://www.cnblogs.com/double-win/p/3888399.html 正文: 最近开始着手进行Openwrt平台的物联网网关设 ...
- Android移动APP开发笔记——Cordova(PhoneGap)通过CordovaPlugin插件调用 Activity 实例
引言 Cordova(PhoneGap)采用的是HTML5+JavaScript混合模式来开发移动手机APP,因此当页面需要获取手机内部某些信息时(例如:联系人信息,坐标定位,短信等),程序就需要调用 ...
- Android移动APP开发笔记——最新版Cordova 5.3.1(PhoneGap)搭建开发环境
引言 简单介绍一下Cordova的来历,Cordova的前身叫PhoneGap,自被Adobe收购后交由Apache管理,并将其核心功能开源改名为Cordova.它能让你使用HTML5轻松调用本地AP ...
- 开发笔记:基于EntityFramework.Extended用EF实现指定字段的更新
今天在将一个项目中使用存储过程的遗留代码迁移至新的架构时,遇到了一个问题——如何用EF实现数据库中指定字段的更新(根据UserId更新Users表中的FaceUrl与AvatarUrl字段)? 原先调 ...
- Lucene/Solr搜索引擎开发笔记 - 第1章 Solr安装与部署(Jetty篇)
一.为何开博客写<Lucene/Solr搜索引擎开发笔记> 本人毕业于2011年,2011-2014的三年时间里,在深圳前50强企业工作,从事工业控制领域的机器视觉方向,主要使用语言为C/ ...
随机推荐
- 解决Genymotion下载设备失败的方法(Connection Timeout)
一直下载不下来,报错. 解决办法: 打开 C:\Users\用户名\AppData\Local\Genymobile目录 打开genymotion.log文件,在里面最下面几行,找到如下日志 [Deb ...
- 容易被忽略的事----sql语句中select语句的执行顺序
关于Sql中Select语句的执行顺序,一直很少注意这个问题,对于关键字的使用也很随意,至于效率问题,因为表中的数据量都不是很大,所以也不是很在意. 今天在一次面试的时候自己见到了,感觉没一点的印象, ...
- java-testng-selenium优化
由于项目中webui测试的需要,是用testng+selenium的方式,其中遇到过几个问题,记录下,方便以后查看 1.重复运行多次case 因为是selenium,所以有的时候需要运行多次,方法是写 ...
- 关于HTML中,绝对定位,相对定位的理解...(学习HTML过程中的小记录)
关于HTML中,绝对定位,相对定位的理解...(学习HTML过程中的小记录) 作者:王可利(Star·星星) HTML中 相对定位:position:relative; 绝对定位:position ...
- struct的成员对齐问题-结构体实际大小问题
struct的成员对齐 注意:为了方便说明,等号左边是每个数据单独所占长度,右边是最终空间大小,以字节为单位. 一.什么时间存在对其问题:(32位机对齐方式是按照4字节对其的,以下所有试验都是在32位 ...
- Node.js中的模块化
每天一篇文章来记录记录自己的成长吧.大二,该静心了.加油~ 好了,废话不多说,今天说说nodejs中的模块化.(注:此文为自己对书nodejs实战的总结) nodejs一个重要的特性就是模块化,模块就 ...
- Xcode全局断点
1.将导航器视图切换到断点导航器视图下,也可以用快捷键Command+7一步搞定,键盘是window风格的用户Command键是win键(有微软logo),然后点击左下角的+号,选择Add Symbo ...
- scjp考试准备 - 5 - 重载和重写
如下代码,在所指示的位置插入代码能够正常编译: class Alpha{ public void bar(int... x){}; public void bar(int x){}; } public ...
- windows下的node-canvas历程
背景:由于在前期开发的过程中,对前端的小图片采用了css-sprite,开始的时候都是在http://spritegen.website-performance.org/站点上合成图片及样式的,但是某 ...
- 四则运算小程序测试--c++--软件工程课
一.测试内容: 1.生成题目数是否准确?2.打印方式(列数l.行间距jj)是否准确?3.有无乘除法cc是否准确?4.数的范围fw是否准确?5.除法有无余数c是否准确?6.加减有无负数f是否准确? 二. ...