public static ObjectPool me; //池的存储 //TODO 此处value使用自定义封装类型而不是单纯的queue更健全 private Dictionary<string, Queue<GameObject>> pool; //每个池中最大数量 //TODO 应该每个池设置每个池单独的数量 private int maxCount = int.MaxValue; public int MaxCount { get { return maxCount;...
当需要从池中拿出一个元素时,使用pool.Get()方法,需自行激活。 当将元素放回池时,使用pool.Release(obj)即可。 代码 MyUnityObjPool.cs publicclassMyUnityObjPool<T>where T:Component{privateTransform _root;privateT _template;protectedT Template=>_template;privateIObjectPool<T>_pool;publicMyUnityObjPool...
ObjectPoolMgr会根据传入的类型type,调用_getpool(type)找到对应的Pool,再从其中取一个对象返回。 代码中_getpool(string type)是ObjectPoolMgr中的私有方法。前面说过,ObjectPoolMgr有一个成员poolDic用来记录已创建的对象池实例,_getpool方法先去poolDic中查找,找到直接返回。如果找不到说明还未创建,使用反射创建对...
</param> public void Shrink(object sender, GameEventArgs eventArgs) { //how many objects are we trying to remove here? int objectsToRemoveCount = pooledObjects.Count - initialPoolSize; //Are there any objects we need to remove? if (objectsToRemoveCount <= 0) { //cool lets get out of...
18. public GameObject Prefab { get =>prefab; set => prefab = value; } 20. public ObjectPool() 21. { 22. m_MaxCount = m_DefaultMaxCount; 23. m_PoolQueue = new Queue<GameObject>(); 24. } 26. public virtual void Init(string poolName, Transform transform) ...
在上面的例子中,poolofMyClass池对象需要显示申明在类级别作用域。显然,当我们需要一个其它类型的对象池时就需要重新申明一个。或许我们可以实现一个对用户透明。 创建管理所有类型池的ObjectPool。 一些对象池类库管理了太多种类的可怕的资源(如内存,数据库连接,游戏对象,外部资产等)。这无疑增加了对象池的代码复杂...
public ObjectPool() { m_MaxCount = m_DefaultMaxCount; m_PoolQueue = new Queue<GameObject>(); } public virtual void Init(string poolName, Transform transform) { m_PoolName = poolName; m_Parent = transform; } public virtual GameObject Get(Vector3 pos, float lifetime) ...
代码中_getpool(string type)是ObjectPoolMgr中的私有方法。前面说过,ObjectPoolMgr有一个成员poolDic用来记录已创建的对象池实例,_getpool方法先去poolDic中查找,找到直接返回。如果找不到说明还未创建,使用反射创建对象池,记录入poolDic,代码如下 使用_getpool获得了对象池实例后,会调用对象池的alloc方法分配一个对...
Vector3 dir= hit.point -Camera.main.transform.position;//从对象池中获取对象GameObject bullet = ObjectPool.GetInstance().GetObj("Bullet"); bullet.transform.position=Camera.main.transform.position; bullet.GetComponent<Rigidbody>().velocity = dir.normalized *speed; ...
ObjectPool.GetInstance().RecycleObj(gameObject); } } 复制代码 Demo.cs 用于简单的使用对象池技术 usingUnityEngine; usingUtilty; publicclassDemo:MonoBehaviour { privatevoidUpdate() { if(Input.GetKeyDown(KeyCode.J)) { GameObject go = ObjectPool.GetInstance().SpawnObject("Prefab"); ...