Unity3d中实现对象池(简化版)

为了节约内存,我们经常不是不断的创建与销毁物体,而是将创建出来的 物体统一放在一个池子中,不需要用到时则将其Active设置为false,需要用到时再设置为true,这样可以大大提高游戏运行效率。

下面是代码主启动代码Game.cs与对象池代码SmallPool.cs,首先需要在Unity3d工程下创建Resources文件夹,并放置一个Cube作为预制体在文件夹内。

SmallPool.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

public class SmallPool : MonoBehaviour
{
    public static SmallPool instance;
    private string objectName;
    private Dictionary<int,GameObject> list=new Dictionary<int, GameObject>();

    private void Awake()
    {
        instance = this;
    }
    public string ObjectName
    {
        get
        {
            return objectName;
        }
        set
        {
            objectName = value;
        }
    }

    public GameObject TakeOut()
    {      
        foreach(var go in list.Values)
        {
            if (go!=null&&!go.activeSelf)
            {
                go.SetActive(true);
                return go;
            }
        }
        GameObject goo = Resources.Load<GameObject>(objectName);
        goo=GameObject.Instantiate(goo);
        list.Add(list.Count, goo);
        return goo;
    }
    public void PutOn(GameObject go)
    {
        go.SetActive(false);
    }
    public void UnSpawnAll()
    {
        foreach (var go in list.Values)
        {
            go.SetActive(false);
        }
    }
}

Game.cs:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

[RequireComponent(typeof(SmallPool))]
public class Game : MonoBehaviour
{
    private SmallPool pool;
    private void Start()
    {
        pool = SmallPool.instance;
        pool.ObjectName = "Cube";
    }
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.V))
        {
           GameObject go= pool.TakeOut();
            Debug.Log("233");
            StartCoroutine(DelayUnSpawn(go));
        }
    }
    IEnumerator DelayUnSpawn(GameObject go)
    {
        yield return new WaitForSeconds(3);
        pool.PutOn(go);
    }
}

 
 

创建一个游戏物体,把Game代码挂在上面,运行后键入v即可看到回收、生成的效果。当然这里的只是小池子,即每实例化不同的预制体都需要创建一个相应的SmallPool脚本对应,实际应用中比较麻烦,下一篇是完整版的对象池代码。Unity3d对象池(全)



猜你喜欢

转载自blog.csdn.net/qq_36927190/article/details/79472252
今日推荐