【Unity 框架】QFramework v1.0 使用指南 工具篇:11. PoolKit 对象池套件 | Unity 游戏框架 | Unity 游戏开发 | Unity 独立游戏

SimpleObjectPool 简易对象池

class Fish
{
    
    
             
}

var pool = new SimpleObjectPool<Fish>(() => new Fish(),initCount:50);
 
Debug.Log(pool.CurCount);
// 50 
var fish = pool.Allocate();
 
Debug.Log(pool.CurCount);
// 49
pool.Recycle(fish);

Debug.Log(pool.CurCount);
// 50


// ---- GameObject ----
var gameObjPool = new SimpleObjectPool<GameObject>(() =>
{
    
    
    var gameObj = new GameObject(""AGameObject"");
    // init gameObj code 

    // gameObjPrefab = Resources.Load<GameObject>(""somePath/someGameObj"");
                
    return gameObj;
}, (gameObj) =>
{
    
    
    // reset code here
});

SafeObjectPool 安全对象池

class Bullet :IPoolable,IPoolType
{
    
    
    public void OnRecycled()
    {
    
    
        Debug.Log(""回收了"");
    }
 
    public  bool IsRecycled {
    
     get; set; }
 
    public static Bullet Allocate()
    {
    
    
        return SafeObjectPool<Bullet>.Instance.Allocate();
    }
             
    public void Recycle2Cache()
    {
    
    
        SafeObjectPool<Bullet>.Instance.Recycle(this);
    }
}
 
SafeObjectPool<Bullet>.Instance.Init(50,25);
             
var bullet = Bullet.Allocate();
 
Debug.Log(SafeObjectPool<Bullet>.Instance.CurCount);
             
bullet.Recycle2Cache();
 
Debug.Log(SafeObjectPool<Bullet>.Instance.CurCount);
 
// can config object factory
// 可以配置对象工厂
SafeObjectPool<Bullet>.Instance.SetFactoryMethod(() =>
{
    
    
    // bullet can be mono behaviour
    return new Bullet();
});
             
SafeObjectPool<Bullet>.Instance.SetObjectFactory(new DefaultObjectFactory<Bullet>());
 
// can set
// 可以设置
// NonPublicObjectFactory: 可以通过调用私有构造来创建对象,can call private constructor to create object
// CustomObjectFactory: 自定义创建对象的方式,can create object by Func<T>
// DefaultObjectFactory: 通过 new 创建对象, can create object by new 

基本的数据结构封装 List、Dictionary

var names = ListPool<string>.Get()
names.Add(""Hello"");

names.Release2Pool();
// or ListPool<string>.Release(names);
var infos = DictionaryPool<string,string>.Get()
infos.Add(""name"",""liangxie"");

infos.Release2Pool();
// or DictionaryPool<string,string>.Release(names);

更多内容

猜你喜欢

转载自blog.csdn.net/u010125551/article/details/127357710