/// <summary> /// 创建一个新的对象 /// </summary> /// <returns></returns> private ItemEntity CreateNewItem() { if (null == rawResResponse) { return null; } ItemEntity result = null; var go = rawResResponse.Instantiate(); if (null != go) { go.transform.position = HKCommonDefine.OUT_SPACE; result = go.gameObject.AddComponent<ItemEntity>(); result.ParentGroupName = rawObjectName; // 设置Group节点 } else { this.Error("raw response Instantiate 创建失败"); } return result; }
/// <summary> /// 获取一个空闲对象 /// </summary> /// <returns></returns> public GameObject GetFree() { if (null == rawResResponse) { return null; } ItemEntity result = null; if (FreePools.Count <= 0) { result = CreateNewItem(); if (null != result) { result.transform.parent = groupNodeTransform; // 默认放在内存池节点下 } } else { // 先从尾部pop出去 result = FreePools.Pop(); if (null == result) // 如果是回收时的对象已经是空对象,被Destroy掉了,那么取出来的时候,仍然可能是空的 { result = CreateNewItem(); // new的时候已经插入到链表头部了 } } if (null != result) { result.PoolInitEvent(); result.gameObject.SetActive(true); // 默认显示出来 result.hideFlags = HideFlags.None; UsePools.Push(result); // 添加到使用队列中 return result.gameObject; } return null; }
/// <summary> /// 回收 /// </summary> /// <param name="_t"></param> public void Recover(GameObject _t) { if (null == _t) { this.Warr("回收的对象为空,放弃回收"); return; } ItemEntity poolEntity = _t.GetComponent<ItemEntity>(); if (null == poolEntity) { this.Error("pool entity组件为空,无法回收"); return; } if (FreePools.Count < MaxCount) { poolEntity.PoolRecoverEvent(); // 回收之前执行的事件 // 执行回收事件 OnRecoverAction(poolEntity); // push到Free队列中 FreePools.Push(poolEntity); } else { poolEntity.IsDestroyTag = true; // 做一个标记,判断是否是非法销毁 if (null != rawResResponse) { rawResResponse.Destroy(_t); } } // 从使用队列中移除 UsePools.Remove(poolEntity); }