对象池写法

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

public enum ObjectType //枚举类型 放入对象池的种类
{
    Shell,
    WereWolf,
    GoldWolf,
    WolfBoss,
    WolfNormal
}
public class Level1Manager : MonoBehaviour {
    static Level1Manager s_Instance;//单例
    Dictionary> m_ObjectPool;//我的对象池
    Dictionary m_ObjectPre;//我的所有预制体
    public static Level1Manager Instance
    {
        get
        {
            return s_Instance;
        }
    }
    void Awake()
    {
        s_Instance = this;
    }
    // Use this for initialization
    void Start () {
        m_ObjectPool = new Dictionary>();//给对象池开辟空间
        m_ObjectPre = new Dictionary();
        m_ObjectPre[ObjectType.WereWolf] = Resources.Load(GameDefine.WereWolfPath) as GameObject;
        m_ObjectPre[ObjectType.GoldWolf] = Resources.Load(GameDefine.GoldWolfPath) as GameObject;
        m_ObjectPre[ObjectType.WolfBoss] = Resources.Load(GameDefine.WolfBossPath) as GameObject;
        m_ObjectPre[ObjectType.WolfNormal] = Resources.Load(GameDefine.WolfNormalPath) as GameObject;
        m_ObjectPre[ObjectType.Shell] = Resources.Load(GameDefine.ShellPath) as GameObject;
    }   
    /// 
    /// 创建水果
    /// 
    /// 
    /// 
    /// 
    public GameObject CreatObject(ObjectType objecttype,Vector3 bornPos,Vector3 bornRot)
    {
        GameObject m_Obj;
        if (!m_ObjectPool.ContainsKey(objecttype))//如果字典里没有此Key值
        {
            m_ObjectPool.Add(objecttype, new List());//添加此Key
        }
        if (m_ObjectPool[objecttype].Count == 0)//如果对应对象池类型里面没有元素
        {
            m_Obj = Instantiate(m_ObjectPre[objecttype], bornPos, Quaternion.Euler(bornRot));
        }
        else
        {
            m_Obj = m_ObjectPool[objecttype][0];
            m_ObjectPool[objecttype][0].SetActive(true);//显示敌人
            m_ObjectPool[objecttype][0].transform.position = bornPos;
            m_ObjectPool[objecttype][0].transform.rotation = Quaternion.Euler(bornRot);
            m_ObjectPool[objecttype].Remove(m_Obj);
        }
        return m_Obj;
    }
    /// 
    /// 销毁水果
    /// 
    public void DestroyObject(GameObject obj)
    {
        obj.SetActive(false);//隐藏敌人
        ObjectPoolType temp = obj.AddComponent();//获取对象池类组件
        if (!m_ObjectPool.ContainsKey(temp.m_ObjType))//如果字典里没有此Key值
        {
            m_ObjectPool.Add(temp.m_ObjType, new List());//添加此Key
        }
        m_ObjectPool[temp.m_ObjType].Add(obj);//按照对象类型加入对象池
    }
}

你可能感兴趣的:(unity3d)