c#无限衍生平台——会不会造成延迟?

本文关键字:延迟 会不会 平台 无限 | 更新日期: 2023-09-27 18:16:10

好吧,我在Unity和c#中工作,并创建了一些简单的函数来根据玩家的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;
    }

这些都是有效的,但是我担心从长远来看,如果每次玩家在上一个生成区域的20个左右单位内生成大约10个新"区域",将会积累并造成大量游戏对象的滞后。

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

c#无限衍生平台——会不会造成延迟?

创建和销毁对象是非常昂贵的,这是你在游戏运行过程中应该避免的事情。

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