Unity 对象池,资源池

 

首先在场景中建立一个Sphere球体,给它加上刚体,作为接下来要用的子弹。然后将其拖到Asset下做成Prefab.

Shoot、BulletPool脚本挂在摄像机上。给BulletPool中BulletPrefab赋值。(将Sphere预制体拖进去就ok)

运行就可以看到结果。

注意:Shoot脚本中加粗的一步很重要,当时笔者未加此步骤时出现了Bug,会出现偶尔实例化不出来的现象。

-----------------------------------------------------------------------------------------------------

Shoot脚本发射子弹的脚本挂在摄像机上。

-----------------------------------------------------------------------------------------------------

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

public class Shoot : MonoBehaviour {
    private BulletPool bulletPool;
    void Start () {
        bulletPool = this.GetComponent();
        
    }
    
    void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            GameObject go = bulletPool.GetBullet();
            go.SetActive(true);
            go.transform.position = transform.position;//非常重要的一步,否则会出现实例化不出来的现象
            go.GetComponent().velocity = transform.forward * 15;
            StartCoroutine(DestroyBullet(go));
            
        }
    }
    IEnumerator DestroyBullet(GameObject bullet)
    {
        yield return new WaitForSeconds(3);
        bullet.gameObject.SetActive(false);
    }
}

------------------------------------------------------------------------------------------------------------------------------

BulletPool脚本挂在摄像机上。当按下鼠标左键,会从对象池中获取子弹。

-------------------------------------------------------------------------------------------------------------------------------

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

public class BulletPool: MonoBehaviour {

    public GameObject bulletPrefab;
    public int poolCount = 30;
    private List bulletList = new List();
    void Start () {
        InitPool();
    }
    public void InitPool() {
        for(int i = 0; i < poolCount; i++)
        {
            GameObject go = GameObject.Instantiate(bulletPrefab);
            go.transform.parent = this.transform;
            go.SetActive(false);
            bulletList.Add(go);
        }
    }
    public GameObject GetBullet()
    {
        foreach(GameObject go in bulletList)
        {
            if (go.activeInHierarchy == false)
                return go.gameObject;
        }
        return null;
    }
}

 

 

如果文章对你有帮助,请她喝杯奶茶吧~

你可能感兴趣的:(Unity3d)