using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public enum ObjectType//两种子弹的枚举
{
cubeBullet,
sphereBullet,
}
public class MyPool : MonoBehaviour {
//定义单例,方便调用
private static MyPool poolInstance;
//生成对象预设体
public GameObject cubeBulletPrefab;
public GameObject sphereBulletPrefab;
//对象类型与预设体的映射关系
private Dictionary<ObjectType,GameObject> typeMatchPrefab=new Dictionary<ObjectType,GameObject>();
private Dictionary<ObjectType, List<GameObject>> pool = new Dictionary<ObjectType, List<GameObject>>();
public static MyPool PoolInstance
{
get { return MyPool.poolInstance; }
}
void Start () {
poolInstance = this;
typeMatchPrefab.Add(ObjectType.cubeBullet,cubeBulletPrefab);
typeMatchPrefab.Add(ObjectType.sphereBullet,sphereBulletPrefab);
}
public GameObject GetObjectInPool(ObjectType ot,Vector3 pos)
{
GameObject go;
//先判断池子中是否有该类型的小池子,并且小池子中是否有对象存在
if (pool.ContainsKey(ot) && pool[ot].Count > 0)
{
go = pool[ot][0];//取出池子中的第一个对象
pool[ot].RemoveAt(0);//池子中移除该对象
go.SetActive(true);//激活对象
}
//若没有该类型的小池子,或者小池子没有对象,则实例化一个游戏对象给它
else
{
go= GameObject.Instantiate(typeMatchPrefab[ot])as GameObject;
}
go.transform.position = pos;
return go;
}
public void PushPool(ObjectType ot,GameObject go)
{
//取消激活对象
go.SetActive(false);
//判断池子中是否有该子池子,没有则创建一个,放进去
if (pool.ContainsKey(ot))
{
pool[ot].Add(go);
}
else
{
pool[ot] = new List<GameObject> { go };
}
}
}
using UnityEngine;
using System.Collections;
public class MyFight : MonoBehaviour {
public Transform cubeBulletStartPos;
public Transform sphereBulletStartPos;
public float force = 15f;
void Update () {
if (Input.GetMouseButtonDown(0))
{
GameObject go = MyPool.PoolInstance.GetObjectInPool(ObjectType.cubeBullet, cubeBulletStartPos.position);
go.GetComponent<Rigidbody>().AddForce(force * go.transform.forward);
StartCoroutine(DestroyObject(ObjectType.cubeBullet, go));
}
if (Input.GetMouseButtonDown(1))
{
GameObject go = MyPool.PoolInstance.GetObjectInPool(ObjectType.sphereBullet, sphereBulletStartPos.position);
go.GetComponent<Rigidbody>().AddForce(force * go.transform.forward);
StartCoroutine(DestroyObject(ObjectType.sphereBullet, go));
}
}
public IEnumerator DestroyObject(ObjectType ot, GameObject go)
{
yield return new WaitForSeconds(1f);
go.GetComponent<Rigidbody>().velocity = Vector3.zero;
MyPool.PoolInstance.PushPool(ot, go);
}
}
对象池
最新推荐文章于 2022-01-11 16:04:57 发布