简单子弹资源池

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

public class BulletPool : MonoBehaviour {

    public float poolCount = 30;
    public GameObject bulletPrefab;
    private List<GameObject> bulletList = new List<GameObject>();
    private void Start()
    {
        InitPool();
    }
    //初始化池子
    void InitPool()
    {
        for(int i = 0; i < bulletList.Count; i++)
        {
            GameObject go = GameObject.Instantiate(bulletPrefab);
            bulletList.Add(go);
            go.SetActive(false);
            go.transform.parent = this.transform;
        }
    }
    GameObject GetBullet()
    {
        foreach (GameObject go in bulletList)
        {
            if (go.activeInHierarchy == false)
            {
                go.SetActive(true);
                return go;
            }
        }
        return null;
    }
}

shoot脚本

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

public class Shoot : MonoBehaviour {
    public GameObject bulletPrefab;
    private BulletPool bulletPool;
    private void Start()
    {
        bulletPool = GetComponent<BulletPool>();
    }
    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            GameObject go = bulletPool.GetBullet();
            go.GetComponent<Rigidbody>().velocity = transform.forward * 50;
            StartCoroutine(DestoryBullet(go));
        }
    }
    IEnumerator DestoryBullet(GameObject go)
    {
        yield return new WaitForSeconds(3);
        go.SetActive(false);
    }

}

猜你喜欢

转载自blog.csdn.net/qq_35669619/article/details/79423472