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

时间:2016-11-04 03:05:59

标签: c# unity3d indefinite

好吧,我在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;
    }

这一切都有效,但是从长远来看,我担心这会产生大约10个新的&#34;部门&#34;每当玩家在20左右的时候,最后产生的部门的单位将建立并从众多游戏对象中产生滞后。

我没有无限期产卵经验 - 这会有问题吗?或者这是无限期产卵的好习惯吗?

1 个答案:

答案 0 :(得分:6)

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

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