加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

Unity子弹池(对象池)的写法

(2017-09-21 12:32:49)
标签:

c

unity3d

vr

分类: Unity

第一个脚本,对象池,产生子弹:

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

public class BulletPool : MonoBehaviour {

    //对象池—产生子弹
    public static BulletPool bulletPoolInstance;  //子弹池实例
    public GameObject bulletObj;    //子弹预设体
    public int pooledAmount = 12;   //子弹池初始大小

    private List pooledGameObjects;  //子弹池集合
    private int nowIndex;   //当前索引号

 void Awake ()
    {
        bulletPoolInstance = this;   //把本对象作为实例
 }

    void Start()
    {
        pooledGameObjects = new List();  //初始化子弹池
        for (int i = 0; i < pooledAmount; i++)
        {

            //创建子弹对象
            GameObject obj = Instantiate(bulletObj,transform.position,Quaternion.identity);  
            obj.SetActive(false);    //设置子弹无效
            pooledGameObjects.Add(obj);   //添加到子弹池中
        }
    }

    //获取对象池中可以使用的子弹
    public GameObject GetPooledObject()  
    {
        for (int i = 0; i < pooledGameObjects.Count; i++)  //把对象池遍历一遍
        {
            //从上一次使用过的子弹的下一个开始遍历(减少遍历次数)
            int item = (nowIndex + i) % pooledGameObjects.Count;
            //找到没有激活的子弹并返回
            if(pooledGameObjects[item].activeInHierarchy == false)
            {
                nowIndex = (item + 1) % pooledGameObjects.Count;
                return (GameObject)pooledGameObjects[item];
            }
        }

        //如果遍历完子弹池发现没有可用的,执行下面
        //实例化子弹,添加到子弹池中
        GameObject obj = (GameObject)Instantiate(bulletObj, transform.position, Quaternion.identity);
        obj.SetActive(false);
        pooledGameObjects.Add(obj);
        return obj;
    }
}

第二个脚本,需要时获取子弹池中的子弹:

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

public class BulletGet : MonoBehaviour {

    public Transform shootSpawn; //子弹发射位置
 void Update ()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            //获取子弹池中的子弹
            GameObject bullet = BulletPool.bulletPoolInstance.GetPooledObject();
            if (bullet != null)
            {
                bullet.transform.position = shootSpawn.position;
                bullet.SetActive(true);
            }
        }
    }
}

第三个脚本,回收子弹:

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

public class BulletRecycle : MonoBehaviour {

    //对象池—子弹回收
    public void OnTriggerEnter(Collider other)
    {
        other.gameObject.SetActive(false);  //取消激活状态
    }
}

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有