[Unity] 对象池

[Unity] ObjectPool

1.设计

  • IPoolable

    InPooled 用于追踪对象的状态,在/不在池中。

    Pool 用于引用对象所属的对象池,作为标记。

  • Pool

    使用数据结构储存对象。

    构造函数,包括对象池所装的实例对象instance,入池的回调函数OnPooled,池子的初始化大小poolSize,池子是否可以自动扩容fixedSize

    public Pool (T instance, Action<T> onPooled, int poolSize = 10, bool fixedSize = true) {
        this.m_PoolSize = poolSize;
        this.m_FixedSize = fixedSize;
        this.m_Instance = instance;
    
        this.m_OnPooled = onPooled;
    
        for (int i = 0; i < poolSize; i++) {
            T item = GameObject.Instantiate<T> (m_Instance);
            m_Objects.Push (item);
    
            item.Pool = this;
    
            m_OnPooled?.Invoke (item);
    
            item.InPooled = true;
        }
    }
    

    NewFreeClearPool

    public T New () {
        T item = default (T);
    
        if (m_Objects.Count > 0) {
            item = m_Objects.Pop ();
        } else {
            if (!m_FixedSize) {
                m_PoolSize++;
            } else {
                Debug.LogWarning ("No object avaliable, Create new Instance!");
            }
    
            item = GameObject.Instantiate<T> (m_Instance);
            item.Pool = this;
        }
    
        if (item) {
            item.InPooled = false;
        }
        return item;
    }
    
    public void Free (T item) {
        if (!item) {
            Debug.LogError ("Null refrence"); return;
        }
    
        if (item.Pool == this && !item.InPooled) {
            if (!m_FixedSize || m_PoolSize > m_Objects.Count) {
    
                m_Objects.Push (item);
    
                m_OnPooled?.Invoke (item);
    
                item.InPooled = true;
            } else {
                GameObject.Destroy (item.gameObject);
                Debug.LogWarning ("Instance can't return to Pool,destroy Instance");
            }
        }
    }
    
    public void ClearPool () {
        foreach (var item in m_Objects) {
            GameObject.Destroy (item);
        }
        m_Objects.Clear ();
        m_OnPooled = null;
    }
    

测试图

2.总结

本案例采用了管理类来管理各种各样的对象池。这样有利于制作可复用的对象池,但需要追踪对象的状态,这需要额外方法来解决,本例中,IPoolable接口中的Pool、InPooled参数用来解决此问题。

除了使用管理类来管理对象池,也可以直接在一个对象内部创建对象池。这样对象的状态由对象自身来管理。这种情况,可以去除Pool、InPooled这两个条件检查,参考Git工程下,Pool.cs中的ObjectPool类。

另外在本例中,使用委托,可以对对象进行一些额外操作,更灵活。

Git地址:https://github.com/Sarofc/UnityTools

参考资料:https://gpp.tkchu.me/object-pool.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值