单例模板类:
using System;
using UnityEngine;
using System.Collections;
using System.Text;
//单例模板
public abstract class SingleTemplate<T> : MonoBehaviour
where T:MonoBehaviour//T泛型继承单例模板的类最终继承哪,约定所有单利类必须是Unity的组件
{
private static T _instance=null;//声明一个私有字段
public static T _Instance//提供只读属性
{
get { return _instance; }
}
//类通过Awake()实例化单例对象,同时可以让子类重写Awake()
protected virtual void Awake()
{
_instance = this as T;
}
}
子对象池:
using UnityEngine;
using System.Collections.Generic;
public class SubPool
{
private GameObject prefab;
Transform tr;
private List<GameObject> subPoolList = new List<GameObject>();
public SubPool(GameObject go,Transform tr)
{
prefab = go;
this.tr = tr;
}
//取对象
public GameObject Spawn()
{
GameObject go;
foreach (GameObject item in subPoolList)
{
if (!item.activeSelf)
{
item.SetActive(true);
return item;
}
}
go = GameObject.Instantiate<GameObject>(prefab);
go.transform.parent = tr;
go.SetActive(true);
subPoolList.Add(go);
return go;
}
//回收对象
public void UnSpawn(GameObject go)
{
if (subPoolList.Contains(go))
{
go.SetActive(false);
}
else
{
Debug.LogError("子对象池中没有该对象");
}
}
/// <summary>
/// 判断子对象是否包含某个对象
/// </summary>
public bool Contains(GameObject go)
{
return subPoolList.Contains(go);
}
}
父对象池:
using UnityEngine;
using System.Collections.Generic;
public class ObjectPool : SingleTemplate<ObjectPool>
{
//用string名字来区分子对象池
private Dictionary<string, SubPool> objectPoolDic;
protected override void Awake()
{
base.Awake();
objectPoolDic = new Dictionary<string, SubPool>();
}
//取对象
public GameObject Spawn(string name, GameObject prefab)
{
GameObject go = null;
if (!objectPoolDic.ContainsKey(name))//没有子对象池
{
CreateSubPool(name, prefab);
}
go = objectPoolDic[name].Spawn();
return go;
}
//回收对象
public void UnSpawn(GameObject go)
{
foreach (SubPool item in objectPoolDic.Values)
{
if (item.Contains(go))
{
item.UnSpawn(go);
return;
}
else
{
Debug.Log("没有改对象!");
}
}
}
//创建子对象池
private void CreateSubPool(string name,GameObject prefab)
{
SubPool sub = new SubPool(prefab, transform);
objectPoolDic.Add(name, sub);
}
}
把父对象池挂空物体上,通过单例访问来使用。