子弹对象池

文章目录

技术细节

对象池

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

public class Pool : MonoBehaviour
{
    public static Pool instance;
    public GameObject bulletPrefab;
    public int bulletCount;
    private Queue<GameObject> queuePool = new Queue<GameObject>();
    private void Awake()
    {
        instance = this;
        FillPool();
    }

   public void FillPool()
   {
        for (int i = 0; i < bulletCount; ++i)
        {
            GameObject newBullet = Instantiate(bulletPrefab,this.transform);
            newBullet.transform.SetParent(this.transform);
            returnPool(newBullet);
        }
   }

    public void returnPool(GameObject gameObject)
    {
        gameObject.SetActive(false);
        queuePool.Enqueue(gameObject);
    }

    public void getFormPool()
    {
        if (queuePool.Count <= 0)
        {
            FillPool();
        }
        var outBullet=queuePool.Dequeue();
        outBullet.SetActive(true);
    }
}


子弹

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

public class Bullet : MonoBehaviour
{

    private  Transform target; //被跟随的物体
    public float speed = 1.0f;

    private void Awake()
    {
        target =GameObject.Find("墙").transform;
    }
    void Update()
    {
    
      transform.Translate((target.position-this.transform.position).normalized *speed);
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {

        if (collision.gameObject.tag == "Enemy")
        {
         Pool.instance.returnPool(this.gameObject);
         this.transform.position = this.transform.parent.position;
        }   
    }
}

玩家

public class Player : MonoBehaviour
{
  
   
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Pool.instance.getFormPool();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值