对象池二

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;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值