文章目录
- 泛型单例类
- 泛型单例类(不带组件版)
- 对象池管理器
- 数据管理器
- 场景管理器
泛型单例类
using System.Collections;
using System.Collections.Generic;
public abstract class ManagersSingle<T> where T : new()
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
instance = new T();
}
return instance;
}
}
}
泛型单例类(不带组件版)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyrSingletonBase<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T Instance {
get
{
return instance;
}
}
protected virtual void Awake() {
instance = this as T;
}
protected virtual void OnDestroy() {
instance = null;
}
}
对象池管理器
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PoolStack{
public Stack <UnityEngine.Object> stack = new Stack<Object>();
public int MaxCount = 100;
public void Push(UnityEngine.Object go){
if (stack.Count < MaxCount) stack.Push(go);
else GameObject.Destroy(go);
}
public UnityEngine.Object Pop() {
if (stack.Count > 0) return stack.Pop();
return null;
}
public void Clear(){
foreach (UnityEngine.Object go in stack) GameObject.Destroy(go);
stack.Clear();
}
}
public class PoolManager :ManagersSingle<PoolManager>
{
Dictionary<string, PoolStack> poolDic = new Dictionary<string, PoolStack>();
public UnityEngine.Object Spawn(string poolName, UnityEngine.Object prefab){
if (!poolDic.ContainsKey(poolName)) poolDic.Add(poolName, new PoolStack());
UnityEngine.Object go = poolDic[poolName].Pop();
if (go == null) go = GameObject.Instantiate(prefab);
return go;
}
public void UnSpawn(string poolName){
if (poolDic.ContainsKey(poolName)){
poolDic[poolName].Clear();
poolDic.Remove(poolName);
}
}
}
数据管理器
场景管理器
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneManager : MyrSingletonBase<SceneManager>
{
public List<string> sceneList = new List<string>();
public int CurrentIndex = 0;
private System.Action<float> currentAction;
private AsyncOperation operation;
public void LoadScene(string sceneName, System.Action<float> action){
currentAction = action;
if (sceneList.Contains(sceneName))
{
CurrentIndex = sceneList.IndexOf(sceneName);
operation = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(sceneName, UnityEngine.SceneManagement.LoadSceneMode.Single);
}
}
void Update(){
if (operation != null){
currentAction(operation.progress);
if (operation.progress >= 1) operation = null;
}
}
public void LoadPre(System.Action<float> action){
CurrentIndex--;
LoadScene(sceneList[CurrentIndex], action);
}
public void LoadNext(System.Action<float> action){
CurrentIndex++;
LoadScene(sceneList[CurrentIndex], action);
}
}