初识对象池

对象池一般应用于一些需要重复使用的物体,比如子弹、陨石,如果直接销毁会产生大量的碎片占用内存空间,最好的方式就是循环利用这些物体,可以创建一个空物体当做对象池,当要使用而没有时就会在对象池里创建一个新的对象,有就直接从对象池里调用,当不需要使用物体时就将物体放回对象池,这里涉及到了一个队列的应用,调用时出队,不用时入队;

public static ObjectPool instance;
    static Queue<GameObject> Pool = new Queue<GameObject>();
    public GameObject bullet;
    GameObject obj;
    public Transform parent;
    void Start () {
        instance = this;
    }
    private void Update()
    {
        Debug.Log("123456");
        if (Input.GetButtonDown("Fire1"))
        {
            StartCoroutine(BulletLife());
        }
    }
    IEnumerator BulletLife()
    {
        obj = Creat(bullet, Vector3.zero, Quaternion.identity);
        obj.GetComponent<Rigidbody>().AddForce(obj.transform.forward * 100);
        yield return new WaitForSeconds(2);
        Delete(obj, parent.position, Quaternion.identity);
    }
    //创建游戏物体-----预制体,出生点,旋转,父物体
    public GameObject Creat(GameObject _prefabs,Vector3 _pos,Quaternion qua)
    {
        GameObject g = null;
        if (Pool.Count>0)
        {
            g = Pool.Dequeue();
            g.SetActive(true);
            g.transform.position = _pos;
        }
        else
        {
            g = Instantiate(_prefabs, _pos, qua);g.transform.SetParent(GameObject.FindGameObjectWithTag("Bullet").transform);
        }
        return g;
    }

    //游戏物体删除-----预制体,回到出生点位置,旋转
    public static void Delete(GameObject _object,Vector3 _resoucesPos,Quaternion qua)
    {
        _object.SetActive(false);
        _object.transform.position = _resoucesPos;
        _object.transform.localRotation = qua;

        Pool.Enqueue(_object);
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值