栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > Cocos2d-x

Unity对象池

Cocos2d-x 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Unity对象池

一、创建一个新的场景,随便创建一个物体,在这个物体上添加控制代码:控制这个物体前后左右,旋转方向。代码如下:
using UnityEngine;
using System.Collections;
//这是一个关于对象池的程序 ,发射20个子弹
public class DuiXiangChi : MonoBehaviour {
 
     void Update () {
        Control();
     
                }
    public void Control()
    {
      
            if (Input .GetKey(KeyCode.W))
            {
                this.transform.Translate(Vector3 .forward * 0.2f);
            }
            if (Input .GetKey(KeyCode.S))
            {
                this.transform.Translate(Vector3 .forward * -0.2f);
            }
    
        if (Input .GetKey(KeyCode.A))
        {
            this.transform.Rotate(Vector3 .up * -1.0f);
        }
        if (Input .GetKey(KeyCode.D))
        {
            this.transform.Rotate(Vector3 .up * 1.0f);
        }
       
    }
}
二、按下鼠标左键, 这个物体开始发射子弹,隔几秒之后消失子弹,并且子弹发射方向随便物体旋转而改变方向。在这里,为了优化内存,我们用的是 对象池。挂在物体身上的代码如下:
using UnityEngine;
using System.Collections;
//这是一个关于对象池的程序 ,发射20个子弹
public class DuiXiangChi : MonoBehaviour {
    public GameObject mFireBall; // 发射子弹的预设体
    private Stack sFireBll = new Stack(); // 声名一个栈
    public static DuiXiangChi _instance;
    public Transform MFirePos;  // 开火位置
                 // Use this for initialization
                 void Start () {
        Create(20);
        _instance = this;
                }
    // 出栈
    GameObject GetObj(Vector3 pos, Quaternion rot)
    {
        if (sFireBll.Count < 2)
        {
           Create(10);
        }
        GameObject obj = sFireBll.Pop() as GameObject;
        obj.transform.position = pos;
        obj.transform.rotation = rot;
        obj.gameObject.SetActive( true);
        return obj;
    }
      public void Recyele(GameObject obj)  // 回收,让子弹自己回收的话,这里是在子弹上调用的。
    {
        obj.gameObject.SetActive( false);
        sFireBll.Push(obj);   // 子弹打出去之后,再回收到栈里。
    }
     void Update () {
        if (Input .GetMouseButtonDown(0))
        {
            GetObj(MFirePos.position, this.transform.rotation  );
        }
    }
}
三、下面是属于写在子弹身上的代码,子弹发出后,利用对象池,子弹自动回收。具体代码如下;
using UnityEngine;
using System.Collections;
public class SpherePao : MonoBehaviour {
private void OnEnable()
{
Invoke("Recycle",3.0f);
}

private void Recycle()
    {   //调用另一个脚本里的对象池自动回收机制
        DuiXiangChi._instance.Recyele(this .gameObject);
    }
                
void Update () {
        transform.Translate( Vector3.forward);   
    }
}

这是游戏效果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/896652.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号