对象池效果图
思路:
听课查询资料都是存储单一物体,突发奇想看看是否能存储不同的物体
分为三个脚本
using System.Collections.Generic;
using UnityEngine;
public class Pool
{
//单例
static Pool _instance;
public static Pool Instance
{
get
{
if(_instance == null)
{
_instance = new Pool();
}
return _instance;
}
}
//池子存放的物体
GameObject obj1;
GameObject obj2;
GameObject obj3;
List<GameObject> pool;
private Pool()
{
//创建list
pool = new List<GameObject>();
//动态获取预制体
obj1 = Resources.Load<GameObject>("Prefabs/prop1");
obj2 = Resources.Load<GameObject>("Prefabs/prop2");
obj3 = Resources.Load<GameObject>("Prefabs/prop3");
}
public GameObject GetObject()
{
GameObject obj;
//随机生成
int i = Random.Range(1, 90);
if (pool.Count == 0)
{
if (i < 30)
{
//创建一个预制体
obj = GameObject.Instantiate(obj1);
//将预制体设置为非激活
obj.SetActive(false);
//给预制体添加组件
obj.AddComponent<Prop>();
//向list加入这个预制体
pool.Add(obj);
}
else if (i < 60)
{
//创建一个预制体
obj = GameObject.Instantiate(obj2);
//将预制体设置为非激活
obj.SetActive(false);
//给预制体添加组件
obj.AddComponent<Prop>();
//向list加入这个预制体
pool.Add(obj);
}
else
{
//创建一个预制体
obj = GameObject.Instantiate(obj3);
//将预制体设置为非激活
obj.SetActive(false);
//给预制体添加组件
obj.AddComponent<Prop>();
//向list加入这个预制体
pool.Add(obj);
}
}
//如果有预制体
//每次取随机
obj = pool[Random.Range(0,pool.Count)];
//激活
obj.SetActive(true);
//并且从pool中移除
pool.RemoveAt(0);
return obj;
}
//回收
public void Recycle(GameObject obj)
{
//设置为非激活
obj.SetActive(false);
//加入pool
pool.Add(obj);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Prop : MonoBehaviour
{
//协程
private void OnEnable()
{
StartCoroutine(Recycle());
}
void Update()
{
//物体移动
transform.Translate(Vector3.forward * 10 * Time.deltaTime);
}
IEnumerator Recycle()
{
//一秒后回收物体
yield return new WaitForSeconds(1f);
Pool.Instance.Recycle(gameObject);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//这个脚本挂在空物体上
public class CreateProp : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
//按空格产生子弹
GameObject prop = Pool.Instance.GetObject();
//初始化位置
prop.transform.position = transform.position;
}
}
}