比如:子弹、敌人
using UnityEngine;
using System.Collections;
public class Main : MonoBehaviour
{
public GameObject bulletPrefab;//子弹预知物
BulletPooling bulletPooling;//对象池类
void Start ()
{
bulletPooling = transform.GetComponent();//获取对象池类
}
void Update ()
{
if (Input.GetMouseButtonDown(0))//如果按下鼠标左键,就发射子弹
{
//GameObject go = (GameObject)GameObject.Instantiate(bulletPrefab, transform.position, transform.rotation);//不使用对象池时只能直接实例化子弹
GameObject go = bulletPooling.GetBullet();//使用对象池时从对象池中获取可用的子弹
if (go != null)//如果获取出可用的子弹
{
go.transform.position = transform.position;//就设置该子弹的位置
go.transform.rotation = transform.rotation;//设置该子弹的转向
go.GetComponent().velocity = transform.forward * 20;//设置子弹的运动方向和速度
//Destroy(go, 3);//不使用对象池时在三秒钟之后直接销毁
}
else
{
go = bulletPooling.CreateBullet();//如果没有可用的子弹就创建一个新的子弹
}
StartCoroutine(DestoryBullet(go));//使用对象池时在三秒钟之后隐藏该子弹
}
}
public IEnumerator DestoryBullet(GameObject go)
{
yield return new WaitForSeconds(3);//等待三秒钟
go.SetActive(false);//将子弹隐藏掉
}
}
对象池类:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class BulletPooling : MonoBehaviour
{
public GameObject bulletPrefab;//子弹预知物
List bulletList;//对象池列表
void Start()
{
bulletList = new List();//实例化对象池列表
}
/// 创建子弹
public GameObject CreateBullet()
{
GameObject go = GameObject.Instantiate(bulletPrefab);//实例化子弹
go.transform.parent = this.transform;//设置子弹的父物体,为了管理
bulletList.Add(go);//把创建出来的子弹添加到对象池列表中
return go;//返回创建的子弹
}
/// 获取子弹
public GameObject GetBullet()
{
foreach (var item in bulletList)//从对象池列表中遍历子弹
{
if (item.activeInHierarchy == false)//如果子弹是隐藏的
{
item.SetActive(true);//说明启用该子弹,就把该子弹显示出来
return item;//返回该子弹
}
}
return null;//如果对象池中没有子弹可用,就返回空
}
}
原文地址:https://blog.csdn.net/qq_32688843/article/details/114986191
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。