【问题标题】:C# infinite spawning of platforms - will it create a lag?C# 无限生成平台——它会造成延迟吗?
【发布时间】:2016-11-04 03:05:58
【问题描述】:

好吧,我在 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# unity3d indefinite


    【解决方案1】:

    创建和销毁对象的成本很高,并且您希望避免在游戏运行时大量执行这些操作。

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

    【讨论】:

    • 谢谢 - 创建/销毁时延迟会明显吗?多少钱算大额?
    • 这完全取决于对象的复杂性和数量。开始吧,使用它,然后决定是否需要优化!
    猜你喜欢
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多