Unity3D一种简单的对象池写法

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
//三种特效
public enum EffectType
{
    BloodSpla,
    FirePhoenix,
    HolyFire,
}
public class EffectManager : BaseManager
{
    private const string Effect_Prefix = "Effect/";//动态加载的特效所在的目录
    private GameObject poolManager;//用来存放实例化出来的特效,界面整洁
    private Dictionary> effectPoolDict = new Dictionary>();//每种特效一个栈

    public override void Init()//项目需要,无视它
    {
        switch (SceneManager.GetActiveScene().name)
        {
            case "001-StartMenu":
                break;
            case "002-MainMenu":
                break;
            default:
                EffectPoolAdd(EffectType.BloodSpla, 20);
                EffectPoolAdd(EffectType.FirePhoenix, 10);
                EffectPoolAdd(EffectType.HolyFire, 10);
                break;
        }
    }
    private GameObject LoadEffect(EffectType effectType)//从Resources中加载特效,可以相应地改为其他加载方式
    {
        return Resources.Load(Effect_Prefix + Enum.GetName(typeof(EffectType), effectType));
    }
    private void EffectPoolAdd(EffectType effectType, int initCount)//需要初始化或者额外添加的特效和数量
    {
        if (poolManager == null)
            poolManager = new GameObject();

        GameObject effectPrefab = LoadEffect(effectType);
        GameObject effectPool = new GameObject(effectType.ToString() + "Pool");
        effectPool.transform.SetParent(poolManager.transform, true);
        Stack effectStack = new Stack();
        for (int i = 0; i < initCount; i++)
        {
            PoolEffect effect = GameObject.Instantiate(effectPrefab, effectPool.transform).GetComponent();
            effect.InjectEffectManager(this);
            effect.transform.SetParent(effectPool.transform);
            effect.Init(poolManager.transform, effectPool.transform, effectType);
            effectStack.Push(effect);
        }
        if (effectPoolDict.ContainsKey(effectType) == false)
            effectPoolDict.Add(effectType, effectStack);
        else
            effectPoolDict[effectType] = effectStack;
    }

    public PoolEffect PopEffect(EffectType effectType)//获取一个特效
    {
        if (effectPoolDict.ContainsKey(effectType) == false)
        {
            Debug.LogError("effectType:" + effectType + "不存在");
            return null;
        }
        if (effectPoolDict[effectType].Count <= 0)
            EffectPoolAdd(effectType, 10);
        return effectPoolDict[effectType].Pop();
    }
    public void PushEffect(EffectType effectType, PoolEffect effect)//使用完毕归还
    {
        effectPoolDict[effectType].Push(effect);
    }

    
}

你可能感兴趣的:(Unity3D)