Unity亚军游戏中的对象池实现(重用)

Object Pooling implementation ( reusing ) in Unity runner game

我有我的第一个跑酷游戏。一切正常。所以,这个问题是关于优化的。

在我的游戏中,有 15 个平台(玩家运行的道路预制件)。随机抽出 15 中的任何 1 被实例化,并且这种情况一直在发生。当玩家通过几个平台时,留下的平台被摧毁。我制作了一个列表来跟踪平台并在最后一个平台预制件(列表[0])中删除它们。并提前实例化新的。

随着游戏的临近,它变得越来越快,这意味着 instantiating/destroying 的操作现在发生得更频繁了。

我阅读了有关对象池的内容。我理解这个概念,并且我强烈认为我应该在我的游戏中使用它。我创建了一个对象池。工作正常。现在我的问题 -

问题 - 我应该如何重用我创建的池中的对象?在我的游戏中,我想出的是 - 用户离开的平台应该从后向前改变位置(用户前进的方向)。我怎样才能做到这一点?

我遵循了这些教程 - https://www.youtube.com/playlist?list=PLLH3mUGkfFCXps_IYvtPcE9vcvqmGMpRK

When player passes a few platforms, The left behind platforms gets destroyed. I made a list to keep track of platforms and delete them last platform prefab ( list[0]). And new ones are instantiated ahead.

有很多方法可以实现对象池化。其中之一包括将对象添加到队列并在使用时将其删除。当您想要 recycle/destroy 它们时,请将它们重新添加到列表中。


How should I reuse object from my created pool?

真的很简单。而不是每次都这样做:

Instantiate(prefab, postion, Quaternion.identity);

游戏开始时在 Start 函数中执行多次,然后存储在 Array/List:

List<GameObject> pool = new List<GameObject>();

void Start()
{
    for (int i = 0; i < 50; i++)
    {
        GameObject tempObj = Instantiate(prefab, postion, Quaternion.identity) as GameObject;
        pool.Add(tempObj);
    }
}

当您需要在游戏过程中实例化对象时,只需从 List/Array:

中获取一个
//Check if object is available in pool
if (pool.Count > 0)
{
    //Object is. Return 1
    GameObject objFromPool = pool[0];
    //Enable the Object
    objFromPool.SetActive(true);
}
else
{
    //Object is NOT. Instantiate new one
    GameObject objFromPool = Instantiate(prefab, postion, Quaternion.identity) as GameObject;
    //Enable the Object
    objFromPool.SetActive(true);
}

当您使用完对象时。不要做 Destroy(objFromPool);,而是重置那个 GameObject 的位置,如果你想的话也可以禁用它,然后将它添加回 List:

//Reset Pos
objFromPool.transform.position = Vector3.zero;
//Disable?
objFromPool.SetActive(false);
//Return back to the array
pool.Add(objFromPool);

最后,最好的方法是将所有对象实例化到一个数组或列表中。使用您递增的整数。整数从0开始递增,直到达到list/array.Length-1。然后您可以使用该整数从池中获取对象。

您可以查看此方法的示例 ArrayObjectPooling 以及如何使用它。