对象池

xiaoxiao2021-02-28  5

using System.Collections; using System.Collections.Generic; using UnityEngine; public enum ObjectType //枚举类型 放入对象池的种类 {     Apple,     Siw,     Melon,     Peach,     Strawberry } public class Level1Manager : MonoBehaviour {     static Level1Manager s_Instance;//单例     Dictionary<ObjectType, List<GameObject>> m_ObjectPool;//我的对象池     Dictionary<ObjectType, GameObject> 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<ObjectType, List<GameObject>>();//给对象池开辟空间         m_ObjectPre = new Dictionary<ObjectType, GameObject>();         m_ObjectPre[ObjectType.WereWolf] = Resources.Load(GameDefine.ApplePath) as GameObject;         m_ObjectPre[ObjectType.GoldWolf] = Resources.Load(GameDefine.PeachPath) as GameObject;         m_ObjectPre[ObjectType.WolfBoss] = Resources.Load(GameDefine.SiwPath) as GameObject;         m_ObjectPre[ObjectType.WolfNormal] = Resources.Load(GameDefine.MelonPath) as GameObject;         m_ObjectPre[ObjectType.Shell] = Resources.Load(GameDefine.Strawberry) as GameObject;     }     /// <summary>     /// 创建水果     /// </summary>     /// <param name="fruit"></param>     /// <param name="bornPos"></param>     /// <param name="bornRot"></param>     public GameObject CreatObject(ObjectType objecttype,Vector3 bornPos,Vector3 bornRot)     {         GameObject m_Obj;         if (!m_ObjectPool.ContainsKey(objecttype))//如果字典里没有此Key值         {             m_ObjectPool.Add(objecttype, new List<GameObject>());//添加此Key         }         if (m_ObjectPool[objecttype].Count == 0)//如果对应对象池类型里面没有元素         {             m_Obj = Instantiate<GameObject>(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;     }     /// <summary>     /// 销毁水果     /// </summary>     public void DestroyObject(GameObject obj)     {         obj.SetActive(false);//隐藏敌人         ObjectPoolType temp = obj.AddComponent<ObjectPoolType>();//获取对象池类组件         if (!m_ObjectPool.ContainsKey(temp.m_ObjType))//如果字典里没有此Key值         {             m_ObjectPool.Add(temp.m_ObjType, new List<GameObject>());//添加此Key         }         m_ObjectPool[temp.m_ObjType].Add(obj);//按照对象类型加入对象池     } }
转载请注明原文地址: https://www.6miu.com/read-200309.html

最新回复(0)