- 最后登录
- 2021-7-6
- 注册时间
- 2012-12-27
- 阅读权限
- 90
- 积分
- 76145
- 纳金币
- 53488
- 精华
- 316
|
网上介绍对象池的文章有很多,但是总感觉代码不太清晰,并不适合新手学习最近在一个工程里看到一段对象池的代码感觉不错,故分享一下- using UnityEngine;
- using System.Collections;
- using System.Collections.Generic;
- using System;
- public class PoolManager : UnitySingleton<PoolManager> {
- public static Dictionary<Type, Stack<IPoolable>> ObjectPoolDic = new Dictionary<Type, Stack<IPoolable>>();
- public static Dictionary<Type, int> ObjectPoolSizeDic = new Dictionary<Type,int>();
-
- void Start () {
- }
-
- public void RegistPoolableType(Type type, int poolSize)
- {
- if (!ObjectPoolDic.ContainsKey(type))
- {
- ObjectPoolDic[type] = new Stack<IPoolable>();
- ObjectPoolSizeDic[type] = poolSize;
- }
- }
-
- public bool HasPoolObject(Type type)
- {
- return ObjectPoolDic.ContainsKey(type) && ObjectPoolDic[type].Count > 0;
- }
-
- public bool IsPoolFull(Type type)
- {
- if (!ObjectPoolDic.ContainsKey(type))
- return true;
- else if (ObjectPoolDic[type].Count >= ObjectPoolSizeDic[type])
- return true;
- return false;
- }
-
- public IPoolable TakePoolObject(Type type)
- {
- if (ObjectPoolDic.ContainsKey(type) && ObjectPoolDic[type].Count > 0)
- {
- return ObjectPoolDic[type].Pop();
- }
- else
- {
- return null;
- }
- }
-
- public bool PutPoolObject(Type type, IPoolable obj)
- {
- if (!ObjectPoolDic.ContainsKey(type) || ObjectPoolDic[type].Count >= ObjectPoolSizeDic[type])
- {
- GameObject.Destroy((obj as MonoBehaviour).gameObject);
- return false;
- }
- else
- {
- (obj as MonoBehaviour).gameObject.SetActive(false);
- //(obj as MonoBehaviour).transform.parent = GameManager.Instance.PoolRoot;
- ObjectPoolDic[type].Push(obj);
- return true;
- }
- }
- }
复制代码 首先继承自一个单例类,就可以用PoolManager.Instance来获取这个类的单例了
定义了两个字典,一个用来对应存储对应的对象类型的栈,一个用来记录实例化的最大个数来控制内存
用的时候Pop,用完了Push
可存储在对象池的对象必须实现IPoolable接口- using UnityEngine;
- using System.Collections;
- public interface IPoolable {
- void Destroy();
- }
复制代码 destroy里可以这样写- if (!PoolManager.Instance.IsPoolFull(GetType()))
- {
- PoolManager.Instance.PutPoolObject(GetType(), this);
- }
- else
- {
- GameObject.Destroy(this.gameObject);
- }
复制代码 |
|