Unity高阶-游戏常用设计模式-简单对象池

当调用对象时,不使用常规的new 构造子的方式,而是通过一个对象池操作。即如果池中存在该对象,则取出;如果不存在,则新建一个对象并存储在池中。当使用完该对象后,则将该对象的归还给对象池。

1、对象池技术并没有限制说只能创建一个对象,而且这种技术同样适用于创建固定数量的对象,然而,这种情况下,你就得面对如何共享对象池里的对象这种问题。

当创建多个对象会的代价会很大的时候,可以考虑使用对象池技术,目前已有的技术比如:线程池技术、数据库连接池技术。

当频繁创建对象,又频繁销毁对象时

IPoolObject

////// 放在对象池里面的对象必须实现的接口

/// public interface IPoolObject {/// /// Object初始化时调用

/// void Init();/// /// Object回收时调用

/// void Release();

BasePoolObject

using UnityEngine;

using System.Collections;

public class BasePoolObject : MonoBehaviour,IPoolObject {

public void Init ()

{

Debug.Log("初始化对象,比如位置");

}

public void Release ()

{

Debug.Log("释放对象");

}

}

ObjectPool

using UnityEngine;using System.Collections;using System.Collections.Generic;public class ObjectPool : MonoBehaviour {/// /// 预生成的个数

/// public int preNum;/// /// 对象列表

/// public  Queuepool = new Queue();/// ///要放入的对象的预置

/// public GameObject  poolObjectPefab;void InitPool(){for(int i=0; i();if(comp==null){Debug.LogError("预置上必须绑有实现了IPoolObject接口的类");}comp.Init();pool.Enqueue(obj);obj.SetActive(false);}}/// /// 创建一个对象

/// ///从池里取出对象.public  GameObject RequestObject(){GameObject obj;if(pool.Count!=0){obj = pool.Dequeue();}else{obj = GameObject.Instantiate(poolObjectPefab);}IPoolObject comp = obj.GetComponent();if(comp==null){Debug.LogError("预置上必须绑有实现了IPoolObject接口的类");}obj.SetActive(true);comp.Init();return obj;}/// /// 回收对象

/// ///Object.public void RecoverObject(GameObject obj){IPoolObject comp = obj.GetComponent();

if(comp==null)

{

Debug.LogError("预置上必须绑有实现了IPoolObject接口的类");

}

pool.Enqueue(obj);

comp.Release();

obj.SetActive(false);

}

void Awake () {

InitPool();

}

// Update is called once per frame

void Update () {

}

}

你可能感兴趣的:(Unity高阶-游戏常用设计模式-简单对象池)