C#无限产生平台 - 会不会产生滞后?

sky*_*guy 2 c# indefinite unity-game-engine

好吧,我在C#中使用Unity工作,并且我创建了一些简单的函数来根据玩家的z位置无限地生成一系列平台(游戏对象).一旦游戏对象安全地消失,我会将其删除,并在每次玩家向前移动时调用此更新方法:

void spawnSectorGroup()
    {
        int i = numSectorsToSpawn; //get position of last sectors, when its exceeded by player then delete and spawn again
        while (i >= 0) {
            int j = Random.Range (0, sectors.Length);
            spawnSector (gamePosition.position, sectors [j]);
            i--;
        }
    }
    void checkAndUpdateSectors() 
    {
        //print ("Player pos"+playerPosition.position);
        //print ("last sector"+gamePosition.position);

        if (gamePosition.position.z - playerPosition.position.z <= 20) { //safe value ahead
            print ("theyre almost there, spawn new group");
            print (gamePosition.position.z - playerPosition.position.z);
            spawnSectorGroup ();

        }

        //destroy past ones
        GameObject[] objects = FindObjectsOfType(typeof(GameObject)) as GameObject[];
        //GameObject[] objects = GameObject.FindGameObjectsWithTag("Block");
        foreach (GameObject o in objects) {

            if (o.gameObject.tag == "Block" || o.gameObject.tag == "Cage" || o.gameObject.tag == "Animal" || o.gameObject.tag == "Enemy") {

                if (playerPosition.position.z - o.transform.position.z >= 100) { //safe aways back

                    print ("destroying past object");
                    print (o.transform.position);
                    Destroy (o.gameObject);
                }
            }

        }

    }
void spawnSector(Vector3 relativePosition,GameObject sector){
        GameObject newSector = GameObject.Instantiate (sector, relativePosition, transform.rotation) as GameObject;
        gamePosition.position += newSector.GetComponent<Sector> ().length;
    }
Run Code Online (Sandbox Code Playgroud)

这一切都有效,但是从长远来看,如果每次玩家在20个左右的时间内产生大约10个新的"扇区"时,我会担心最后产生的扇区会产生大量的游戏对象.

我没有无限期产卵经验 - 这会是一个问题吗?或者这是一个无限期产卵的良好做法?

CaT*_*aTs 6

创建和销毁对象非常昂贵,而且您希望在游戏运行时避免大量操作.

查看关于对象池的 Unity教程.基本思想是,不是创建和销毁对象,而是从现有对象池中获取它们,并在完成后返回它们,以便可以重用它们.