-
Notifications
You must be signed in to change notification settings - Fork 2
ObjectPool
AlanZeng edited this page Nov 21, 2018
·
1 revision
ObjectPool 是BlackFire Framework内部提供的功能模块,其目的是对于大量可以重复使用的对象进行有效管理,提供产出、回收、释放、锁等基础功能,以降低应用程序对内存的申请和回收频率,从而提高应用程序运行时的性能。
- GUI 模块扩展
- 用例
1.实现一个对象池所管理的对象
/// <summary>
/// 子弹对象。
/// </summary>
public sealed class BulletObject : ObjectPool.ObjectBase
{
public BulletObject(BulletLogic target)
{
Target = target;
target.ObjectOwner = this;
}
public BulletLogic Target { get; private set; }
protected override void OnSpawn()
{
base.OnSpawn();
Target.transform.position = Vector3.zero;
Target.gameObject.SetActive(true);
}
protected override void OnRecycle()
{
base.OnRecycle();
Target.gameObject.SetActive(false);
}
protected override void OnRelease()
{
base.OnRelease();
GameObject.DestroyImmediate(Target);
Target = null;
}
protected override void OnLock()
{
base.OnLock();
Target.LockState = true;
}
protected override void OnUnlock()
{
base.OnUnlock();
Target.LockState = false;
}
}
2.编写一个子弹逻辑类
/// <summary>
/// 子弹逻辑类。
/// </summary>
public sealed class BulletLogic : MonoBehaviour
{
[SerializeField] private float m_SurvivalTime=5f;
[SerializeField] private float m_BulletSpeed=20f;
public bool LockState { get; internal set; }
public ObjectPool.ObjectBase ObjectOwner { get; internal set; }
private float m_AccumulationTime = 0f;
private void OnEnable()
{
m_AccumulationTime = 0f;
}
private void Update()
{
if (!LockState)
{
m_AccumulationTime += Time.deltaTime;
if (m_AccumulationTime>=m_SurvivalTime)
{
Log.Info("BulletTimetoRecycle");
Event.Fire("Topic://TestBullet/BulletTimetoRecycle", this, EventArgs.Empty);
m_AccumulationTime = 0f;
return;
}
transform.position = Vector3.MoveTowards(transform.position, transform.position+Vector3.left,Time.deltaTime * m_BulletSpeed);
}
}
private void OnTriggerEnter(Collider other)
{
Log.Info("Bullet Hit "+other.gameObject.name);
Event.Fire("Topic://TestBullet/BulletHit",this,EventArgs.Empty);
}
3.使用对象池进行管理
public sealed class ObjectPoolDemo : MonoBehaviour
{
[SerializeField] private BulletLogic m_BulletTemplate;
private ObjectPool.PoolBase m_TestPool = null;
private void Start()
{
//监听事件。
//子弹达到存活时间事件。
Event.On("Topic://TestBullet/BulletTimetoRecycle",this,(sender,args)=> {
m_TestPool.Recycle((sender as BulletLogic).ObjectOwner);
});
//子弹打到物体事件。
Event.On("Topic://TestBullet/BulletHit", this, (sender, args) => {
m_TestPool.Recycle((sender as BulletLogic).ObjectOwner);
});
//对象池弹性增长的,这里设置池的容量为300。
m_TestPool = ObjectPool.CreatePool("TestPool",300);
//对象池设计可以存放不同子类类型对象,只要是继承自ObjectPool.Object。
//下面是给对象池的工厂绑定实例化回调。
m_TestPool.PoolFactoryBinder.AddBinding(typeof(BulletObject),()=>new BulletObject(GameObject.Instantiate<BulletLogic>(m_BulletTemplate)));
}
//界面UI点击FireBullet事件。
public void OnFireBullet()
{
if (m_TestPool.Count<m_TestPool.Capacity)
{
var bulletObject = m_TestPool.Spawn(typeof(BulletObject));
}
}
}