您当前的位置: 首页 >  unity

CoderZ1010

暂无认证

  • 2浏览

    0关注

    168博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Unity SKFramework框架(五)、ObjectPool 对象池

CoderZ1010 发布时间:2022-05-16 08:46:38 ,浏览量:2

目录

简介

一、ObjectPool

1.分配对象

2.回收对象

3.缓存数量

4.释放对象池

二、MonoObjectPool

1.创建方法

2.分配对象

3.回收对象

4.缓存数量

5.释放对象池

简介

        框架中将对象池划分为两种,一种是通过new运算符创建对象的对象池,另一种是对象类继承自MonoBehaviour,需要自定义创建方法的对象池,我们将它们分别称为ObjectPool、MonoObjectPool。

        为需要实现对象池管理的对象类继承IPoolable接口,接口中包含bool类型字段IsRecycled,用于标记该对象是否已经回收,以及OnRecycled方法,用于实现对象的回收事件。

一、ObjectPool

以一个Person类为例,为其继承IPoolable接口,并实现接口中属性和方法:

public class Person : IPoolable
{
    public string Name { get; set; }
    public int Age { get; set; }
    public float Weight { get; set; }

    public bool IsRecycled { get; set; }
    public void OnRecycled()
    {
        Name = null;
        Age = 0;
        Weight = 0f;
    }
}
1.分配对象
public class Example : MonoBehaviour
{
    private void Start()
    {
        //分配对象
        Person person = ObjectPool.Allocate();
        person.Name = "CoderZ";
        person.Age = 28;
        person.Weight = 60f;
    }
}
2.回收对象
public class Example : MonoBehaviour
{
    private void Start()
    {
        //分配对象
        Person person = ObjectPool.Allocate();
        person.Name = "CoderZ";
        person.Age = 28;
        person.Weight = 60f;

        //回收对象
        ObjectPool.Recycle(person);
    }
}
3.缓存数量

        对象池中默认的最大缓存数量为9,可以通过如下方式修改该值,当我们修改该值时,系统会判断池中的数量是否已经大于目标值,如果大于则根据差值进行释放。

//设置对象池的最大缓存数量
ObjectPool.SetMaxCacheCount(100);
4.释放对象池

释放对象池不仅是释放池中的对象,对象池本身也会被释放。

//释放对象池
ObjectPool.Release();
二、MonoObjectPool

以一个Bullet子弹类为例,它挂载于子弹的Prefab预制体上

using UnityEngine;
using SK.Framework;

public class Bullet : MonoBehaviour, IPoolable
{
    public bool IsRecycled { get; set; }

    public void OnRecycled()
    {
        gameObject.SetActive(false);
        transform.localPosition = Vector3.zero;
        transform.localRotation = Quaternion.identity;
    }
}
1.创建方法

Mono类型的对象池,我们在使用之前首先需要自定义一个创建方法:

using UnityEngine;
using SK.Framework;

public class Example : MonoBehaviour
{
    //子弹预制体
    [SerializeField] private GameObject bulletPrefab;

    private void Start()
    {
        MonoObjectPool.CreateBy(() =>
        {
            var instance = Instantiate(bulletPrefab);
            instance.transform.SetParent(transform);
            instance.transform.localPosition = Vector3.zero;
            instance.transform.localRotation = Quaternion.identity;
            instance.SetActive(true);
            Bullet bullet = instance.GetComponent();
            return bullet;
        });
    }
}
2.分配对象
//分配对象
Bullet bullet = MonoObjectPool.Allocate();
3.回收对象
//分配对象
Bullet bullet = MonoObjectPool.Allocate();
//回收对象
MonoObjectPool.Recycle(bullet);
4.缓存数量
//设置对象池的最大缓存数量
MonoObjectPool.SetMaxCacheCount(99);
5.释放对象池
//释放对象池
MonoObjectPool.Release();
关注
打赏
1653184800
查看更多评论
立即登录/注册

微信扫码登录

0.3891s