对象池管理器

一、单个对象池单元

using System.Collections.Generic;
using UnityEngine;
using System;

[Serializable]
public class GameObjectPool {

    [SerializeField]
    public string name;
    [SerializeField]
    private int maxNum;
    [SerializeField]
    private GameObject prefab;

    [NonSerialized]
    private List<GameObject> UnUseList = new List<GameObject>();

    public GameObject Out() {
        
        if (UnUseList.Count > 0) {
            GameObject go = UnUseList[0];
            UnUseList.RemoveAt(0);
            go.SetActive(true);
            return go;
        }

        GameObject newGo = GameObject.Instantiate(prefab);
        return newGo;
    }

    public void In(GameObject obj) {
        
        if (UnUseList.Count >= maxNum) {
            GameObject.Destroy(obj);
            return;
        }

        obj.SetActive(false);
        UnUseList.Add(obj);
    }
}

二、对象池列表

using System.Collections.Generic;
using UnityEngine;

//可编辑的列表,可视化新加对象池
public class GameObjectPoolList : ScriptableObject {
    public List<GameObjectPool> pools = new List<GameObjectPool>();
}

三、对象池管理器

using System.Collections.Generic;
using UnityEngine;

public class PoolManager {

    private static PoolManager _instance;

    public static PoolManager Instance {
        get {
            if (_instance == null)
                _instance = new PoolManager();

            return _instance;
        }
    }

    private Dictionary<string, GameObjectPool> pools;
    public PoolManager() {
        //加载序列化添加的对象池,添加到字典中
        GameObjectPoolList gameObjectPoolList = Resources.Load<GameObjectPoolList>("gameobjectpool");

        pools = new Dictionary<string, GameObjectPool>();
        foreach (GameObjectPool pool in gameObjectPoolList.pools) {
            pools.Add(pool.name, pool);
        }
    }

    public object Out(string Name) {
        GameObjectPool pool;
        pools.TryGetValue(Name, out pool);

        if (pool != null) {
            return pool.Out();
        }

        return null;
    }

    public void In(string Name,GameObject obj) {

        GameObjectPool pool;
        pools.TryGetValue(Name, out pool);

        if (pool != null)
        {
            pool.In(obj);
            return;
        }

        Debug.LogWarning("PoolName:" + Name + "不存在!");
    }
}

生成序列化类的变量的文件(点这里)。对象池的名字可以用配置的形式规定,例如用枚举来做名字等,方便修改等。


首页 我的博客
粤ICP备17103704号