如何使用对象池?

时间:2018-06-29 22:22:21

标签: c# unity3d

对于测试,我只想在地形区域周围生成对象。

对象池脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class SimplePool : MonoBehaviour
{
    [SerializeField]
    private GameObject prefab;

    private Queue<GameObject> availableObjects = new Queue<GameObject>();

    public static SimplePool Instance { get; private set; }

    private void Awake()
    {
        Instance = this;
        GrowPool();
    }

    public GameObject GetFromPool()
    {
        if (availableObjects.Count == 0)
            GrowPool();

        var instance = availableObjects.Dequeue();
        instance.SetActive(true);
        return instance;
    }

    private void GrowPool()
    {
        for (int i = 0; i < 10; i++)
        {
            var instanceToAdd = Instantiate(prefab);
            instanceToAdd.transform.SetParent(transform);
            AddToPool(instanceToAdd);
        }
    }

    public void AddToPool(GameObject instance)
    {
        instance.SetActive(false);
        availableObjects.Enqueue(instance);
    }
}

还有我用于生成的脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnRandomly : MonoBehaviour
{
    [SerializeField]
    private float delay = 0.5f;
    [SerializeField]
    private GameObject spawnPrefab;

    private float lastTime;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update ()
    {
      if (Time.time - lastTime > delay)
        {
            SpawnFromPool();
        }
    }

    private void SpawnFromPool()
    {
        lastTime = Time.time;
        Vector3 position = new Vector3(Random.Range(0, 100), 0, 0);
        Instantiate(spawnPrefab, position, Quaternion.identity);

        SimplePool.Instance.AddToPool(spawnPrefab);
    }
}

两个脚本都附加到层次结构中的同一GameObject。

对于第一个脚本,SimplePool我没有将任何对象关联到Prefab。 我把预制件留空了。

在第二个脚本中,我添加了一个预制件。

但是结果是,在运行游戏时,它会不断生成连续的对象,并且该对象在“层次结构”中为灰色,因此您无法在场景/游戏窗口中看到它们。它从未像对象池那样破坏对象。

Object Pooling

0 个答案:

没有答案