前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >unity3D初识对象池技术

unity3D初识对象池技术

作者头像
py3study
发布2020-01-07 16:06:51
3840
发布2020-01-07 16:06:51
举报
文章被收录于专栏:python3python3python3

对象池概念:用来优化游戏,提升游戏性能,如飞机大战 ,当触及到大量的物体需要不断的重新的被创建的时候,这个时候就适合用到对象池。

下面我会写一个例子更详细的来说明下这个对象池的用法:

  对象池主要有2个方法

     1:从池里去找东西

     2:往池里放东西

这里我是写了一个打砖块的例子,后续我会把整个游戏的代码分享出来,里面包含一个拿和一个放的方法。

using UnityEngine;

using System.Collections;

using System.Collections.Generic; //用字典必须加上这个

public class ObjectPool : MonoBehaviour

{

    public static ObjectPool intance;  //单例模式

    public static Dictionary<string, ArrayList> pool = new Dictionary<string, ArrayList> { };  //字典保存我们要保存的对象

    void Start()

    {

        intance = this;

    }

    //从对象池里拿到我们的对象

    public Object Get(string prefabName, Vector3 position, Quaternion rotation)

    {

        string key = prefabName + "(Clone)";

        Object o;

        if (pool.ContainsKey(key) && pool[key].Count > 0) //判断这个池里有没有要拿的对象 

        {

            ArrayList list = pool[key];

            o = list[0] as Object;

            list.RemoveAt(0);

            //重新初始化相关状态

            (o as GameObject).SetActive(true);

            (o as GameObject).transform.position = position;

            (o as GameObject).transform.rotation = rotation;

        }

        else

        {

            o = Instantiate(Resources.Load(prefabName), position, rotation); //如果池里没有对象了就实例化一个出来 

        }

        // Object o = Instantiate(Resources.Load(prefabName), position, rotation);

        //初似化池里面的数据

        DelayDestroy dd = (o as GameObject).GetComponent<DelayDestroy>();

        dd.Init();

        return o;

    }

    //把对象放回对象池

    public Object Return(GameObject o)

    {

        string key = o.name;

        print("Return key" + key);

        if (pool.ContainsKey(key)) //判断池里是否有我们要拿的对象

        {

            ArrayList list = pool[key];

            list.Add(o);

        }

        else

        {

            pool[key] = new ArrayList() { o };

        }

        o.SetActive(false); //让对象隐藏

        return o;

    }

}

代码2://销毁对象的代码

using UnityEngine;

using System.Collections;

public class DelayDestroy : MonoBehaviour {

    //需要初始化的所有属性

    public void Init() 

    {

        StartCoroutine(ReturnToPool());

    }

    //协程函数

    IEnumerator  ReturnToPool()

    { 

       yield return  new WaitForSeconds (2f);

       ObjectPool.intance.Return(this.gameObject);

    }

}

这是游戏效果

wKioL1Sxe8PxQHqXAAPABGEdx3A056.jpg
wKioL1Sxe8PxQHqXAAPABGEdx3A056.jpg

看到Ball(Clone)就是我们从对象池拿的对象,这样我们就可以提高我们游戏的性能,实现了游戏优化

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档