unity通用对象池

unity通用对象池-适用于各种类型的对象池

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

/// 
/// 通用型对象池
/// 
/// 
public class ObjectPool
{

    private List pool = new List(); 
    private Func func;
    /// 
    /// 构造函数
    /// 
    /// 委托 返回T类型
    /// 数目
    public ObjectPool(Func func,int count)
    {
        this.func = func;
        InstanceObject(count);
    }
    /// 
    /// 获取对象池中对象
    /// 
    /// 
    public T GetObject()
    {
        int i = pool.Count;
        //当对象池数目大于0时直接移除
        while (i-->0)
        {
            T t = pool[i];
            pool.RemoveAt(i);
            return t;
        }
        //当对象池无对象时,生成对象 再递归 调用移除方法
        InstanceObject(3);
        return GetObject();
    }
    /// 
    /// 添加对象
    /// 
    /// 
    public void AddObject(T t)
    {
        pool.Add(t);
    }

    /// 
    /// 实例化对象
    /// 
    /// 
    public void InstanceObject(int count)
    {
        for (int i = 0; i < count; i++)
        {
            pool.Add(func());
        }
    }
}


你可能感兴趣的:(unity通用对象池)