一、子弹生产脚本(简单实用对象池)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletIncubator : MonoBehaviour
{
public static BulletIncubator instance;
public int amountToPool;
public GameObject m_bullet;
public List<GameObject>m_pooledObjectlist;
private void Awake()
{
instance = this;
}
void Start()
{
m_pooledObjectlist = new List<GameObject>();
GameObject tmp;
for (int i = 0; i < amountToPool; i++)
{
tmp = Instantiate(m_bullet,transform);
tmp.SetActive(false);
m_pooledObjectlist.Add(tmp);
}
}
public GameObject GetPooledObject()
{
for (int i = 0; i < amountToPool; i++)
{
if(!m_pooledObjectlist[i].activeInHierarchy)
{
return m_pooledObjectlist[i];
}
}
return null;
}
}
二、发射脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FireBullet : MonoBehaviour
{
public bool IsStart;
public Transform BulletStartPos;
public float bulletspeed;
public Camera mainCamera;
public GameObject Bullet_Obj;
private BulletIncubator m_BulletIncubator;
private float shootingtime = 0.5f;
void Start()
{
mainCamera = Camera.main;
m_BulletIncubator = BulletIncubator.instance;
}
void Update()
{
if(IsStart&& mainCamera!=null)
{
Vector3 inputv3 = Input.mousePosition;
Vector3 pos = mainCamera.WorldToScreenPoint(BulletStartPos.position);
Vector3 m_MousePos = new Vector3(inputv3.x, inputv3.y, pos.z);
BulletStartPos.position = mainCamera.ScreenToWorldPoint(m_MousePos);
if (IsBoolClick ()&& Time.time> shootingtime)
{
shootingtime = Time.time + 0.5f;
Vector3 rayOrigin = BulletStartPos.position;
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray,out hit,300))
{
GameObject go = m_BulletIncubator.GetPooledObject();
go.transform.parent = null;
go.transform.position = BulletStartPos.position;
go.SetActive(true);
go.GetComponent<Rigidbody>().velocity = (hit.point-go.transform.position) * bulletspeed;
}
}
}
}
bool IsBoolClick()
{
return Input.GetMouseButtonDown(0) || Input.touchCount > 0;
}
}
三、子弹脚本 using System.Collections; using System.Collections.Generic; using UnityEngine;
public class BulletObjEvent : MonoBehaviour { // Update is called once per frame void Update() { if(OBJPos()) { transform.gameObject.SetActive(false); transform.parent = BulletIncubator.instance.transform; } } bool OBJPos() { return transform.position.y < -150 || transform.position.y > 150 || transform.position.x < -150|| transform.position.x > 150 || transform.position.z > 150 || transform.position.z < -150; }
}
|