对象池二

来源:互联网 发布:2017淘宝手机首页装修 编辑:程序博客网 时间:2024/05/16 08:58
using UnityEngine;using System.Collections;using System.Collections.Generic;public class PoolMsg : MonoBehaviour {    public static PoolMsg instance;    Dictionary<string, ArrayList> pool = new Dictionary<string, ArrayList>();        void Awake()    {        instance = this;    }   public GameObject GetInPool(string key,Vector3 pos,Quaternion q)    {        string prefabName = key + "(Clone)";        GameObject go;        if (pool.ContainsKey(prefabName) && pool[prefabName].Count > 0)        {            go = pool[prefabName][0] as GameObject;            pool[prefabName].RemoveAt(0);            go.SetActive(true);        }        else        {            go = Instantiate(Resources.Load(key)) as GameObject;            go.transform.SetParent(transform);        }        go.transform.position = pos;        go.transform.rotation = q;        return go;    }    public GameObject ReturnPool(GameObject go)    {        string prefabName = go.name;        if (pool.ContainsKey(prefabName))        {            pool[prefabName].Add(go);        }        else        {            pool[prefabName] = new ArrayList() { go };        }        go.SetActive(false);        return go;    }}//挂在子弹上using UnityEngine;using System.Collections;public class Hide : MonoBehaviour {    [SerializeField]    float delayTime = 2f;    void Update()    {        StartCoroutine(HideBullet());    }IEnumerator HideBullet()    {        yield return new WaitForSeconds(delayTime);        PoolMsg.instance.ReturnPool(this.gameObject);    }}//挂在控制发射的物体上using UnityEngine;using System.Collections;public class TankMove : MonoBehaviour {    [SerializeField]    GameObject buttlePrefab;    [SerializeField]    Transform firePos;    [SerializeField]    float bulletSpeed = 100f;    void Update()    {        Fire();    }    void Fire()    {        if (Input.GetKeyUp(KeyCode.Space))        {         GameObject go=PoolMsg.instance.GetInPool(buttlePrefab.name, firePos.position, firePos.rotation);         go.GetComponent<Rigidbody>().velocity = transform.forward * bulletSpeed;        }    }}

1 0
原创粉丝点击