文章目录
技术细节
对象池
using System.Collections;
using System.Collections.Generic;
using System.Numerics;
using UnityEngine;
public class Pool : MonoBehaviour
{
public static Pool instance;
public GameObject bulletPrefab;
public int bulletCount;
private Queue<GameObject> queuePool = new Queue<GameObject>();
private void Awake()
{
instance = this;
FillPool();
}
public void FillPool()
{
for (int i = 0; i < bulletCount; ++i)
{
GameObject newBullet = Instantiate(bulletPrefab,this.transform);
newBullet.transform.SetParent(this.transform);
returnPool(newBullet);
}
}
public void returnPool(GameObject gameObject)
{
gameObject.SetActive(false);
queuePool.Enqueue(gameObject);
}
public void getFormPool()
{
if (queuePool.Count <= 0)
{
FillPool();
}
var outBullet=queuePool.Dequeue();
outBullet.SetActive(true);
}
}
子弹
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
private Transform target; //被跟随的物体
public float speed = 1.0f;
private void Awake()
{
target =GameObject.Find("墙").transform;
}
void Update()
{
transform.Translate((target.position-this.transform.position).normalized *speed);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Enemy")
{
Pool.instance.returnPool(this.gameObject);
this.transform.position = this.transform.parent.position;
}
}
}
玩家
public class Player : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Pool.instance.getFormPool();
}
}
}