对象池

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GameObjectPool : MonoBehaviour {
    List<GameObject> pools = new List<GameObject>();
private GameObjectPool(){}
    private static GameObjectPool instance;
    public static GameObjectPool GetInstance()
    {
        if (instance==null)
        {
            instance = new GameObject("GameObjectPool").AddComponent<GameObjectPool>();
        }
        return instance;
    }
    //获取一个对象
public GameObject MyInstantiate(GameObject name)
    {
        if (pools.Count==0)
        {
            return Instantiate(name, Vector3.zero, Quaternion.identity) as GameObject;
        }
            //取出一个对象
        else
        {
            GameObject obj = pools[0];
            obj.SetActive(true);
            //将被取出的元素
            pools.Remove(obj);
            return obj;
        }       
    }
    //存取一个对象
    public void MyDisable(GameObject name)
    {
        name.SetActive(false);
        pools.Add(name);
    }

}

using UnityEngine;
using System.Collections;


public class gameManager : MonoBehaviour {


    public GameObject obj;

// Update is called once per frame
void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            GameObjectPool.GetInstance().MyInstantiate(obj);
        }
}
}

using UnityEngine;
using System.Collections;
public class Bullet : MonoBehaviour
{
    void OnEnable()
    {       
        //如果不加这句代码,从对象池中取出的子弹就会从上一次消失的位置开始运动。而不是你设定的子弹生成位置
        transform.position = Vector3.zero;
        //开启协程方法
        StartCoroutine(DelayDisable(3f));
    }




    void Update()
    {
        //子弹生成,自动向前运动
        transform.Translate(Vector3.forward * Time.deltaTime * 20);
    }
    void OnDisable()
    {
        Debug.Log("I'm over");
    }
    //子弹消失的方法
    IEnumerator DelayDisable(float time)
    {
        //等待三秒
        yield return new WaitForSeconds(time);
        //调用单例中向对象池里面存对象的方法
        GameObjectPool.GetInstance().MyDisable(gameObject);
    }


}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值