这是我第一次写博客,博主经验尚浅,还请老铁不吝赐教。
【1.万能单例模式】
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//单例的报错
public class SingletonException : System.Exception{
public SingletonException(string msg) : base(msg){}
}
//万能单例模式
public abstract class Singleton<T> where T : class,new()
{
private static T instance = null;
public static T Instance{
get{
if(instance == null)
instance = new T();
return instance;
}
}
protected Singleton(){
if(instance!=null)
throw new SingletonException("This "+typeof(T).ToString()+" Singleton is not null!");
Init();
}
protected abstract void Init();
}
【2.简易的对象池】
using UnityEngine;
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class PoolManager : Singleton<PoolManager>{
private static GameObject Parent;
public Dictionary<string, List<GameObject>> Pool;
protected override void Init(){
Pool = new Dictionary<string, List<GameObject>>();
Parent = new GameObject();
Parent.name = "Pool";
Parent.SetActive(false);
GameObject.DontDestroyOnLoad(Parent);
}
public void Push(GameObject obj){
if(obj.transform.parent == Parent.transform)
return;
if(!Pool.ContainsKey(obj.name))
Pool.Add(obj.name, new List<GameObject>());
obj.transform.SetParent(Parent.transform);
Pool[obj.name].Add(obj);
obj.SetActive(false);
}
public GameObject Pop(string name, string path = null){
if(string.IsNullOrEmpty(path)&&!path.Contains("/"))
path += "/";
GameObject result = null;
if(!Pool.ContainsKey(name) || Pool[name].Count == 0){
if(path==null){
Debug.LogError("Obj Pool doesn't hava:" + name);
return null;
}
result = Resources.Load(path + name) as GameObject;
if(result==null)
Debug.LogError("Cannot find resource : " + path + name);
result.name = name;
}else
{
var resultList = from obj in Pool[name] where !obj.activeSelf select obj;
result = resultList.First();
if(result.transform.parent!= Parent.transform){
Debug.LogError("obj not in Pool : " + result.name);
}
}
return result;
}
}
闲暇时间写的,没有来的及用在项目上,, 如果有错误请评论或者私信我,我会及时更改,谢谢大家的 支持!