学习笔记
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pool2 : MonoBehaviour
{
public static Pool2 instance;
private GameObject m_FatherObject;//父物体把实例化的物体放入父物体下
private void Awake()
{
instance = this;
if(m_FatherObject==null)
{
m_FatherObject = new GameObject("father");
}
}
Dictionary<string, List<GameObject>> pooldic = new Dictionary<string, List<GameObject>>();
void Update()
{
if (Input.GetMouseButtonDown(0))
{
GetObj("Pool2/Cube");
}
if (Input.GetMouseButtonDown(1))
{
GetObj("Pool2/Sphere");
}
}
/// <summary>
/// 往缓存池放入
/// </summary>
public void PushObj(string name,GameObject obj)
{
obj.SetActive(false);
obj.transform.parent = m_FatherObject.transform;
if (pooldic.ContainsKey(name))
{
//如果有抽屉
pooldic[name].Add(obj);
}
else
{
//如果没有抽屉
pooldic.Add(name,new List<GameObject>() { obj});
}
}
/// <summary>
/// 往外拿物体
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public GameObject GetObj(string name)
{
GameObject obj = null;
//如果有物体
if(pooldic.ContainsKey(name)&&pooldic[name].Count>0)
{
obj = pooldic[name][0];
pooldic[name].RemoveAt(0);
}else
{
//如果没有
obj = GameObject.Instantiate(Resources.Load<GameObject>(name));
obj.name = name;
}
obj.transform.parent = null;
obj.SetActive(true);
return obj;
}
/// <summary>
/// 在跳转场景时清除字典
/// </summary>
public void Clear()
{
pooldic.Clear();
}
}
测试脚本:
一、取出
void Update()
{
if (Input.GetMouseButtonDown(0))
{
GetObj("Pool2/Cube");
}
if (Input.GetMouseButtonDown(1))
{
GetObj("Pool2/Sphere");
}
}
二、放入
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PoolObject2 : MonoBehaviour {
private void OnEnable()
{
Invoke("PushObj",1f);
}
void PushObj()
{
Pool2.instance.PushObj(this.gameObject.name, this.gameObject);
}
}
这个脚本是放到需要实例化预制体上,用时间测试放入是否可以