- Home /
How to update nav mesh without lagging game?
Hi, I'm currently working on a scene where I create a new maze-like level each round, with randomly generated walls, and enemies spawn around the edges of the level and move toward the center. In order to make the enemies path properly, they each have a Nav Mesh Agent and the wall prefabs have Nav Mesh Surfaces. Currently, I call NavMeshBuilder.BuildNavMesh(); after putting in the new walls, and this causes the enemies to properly pathfind around them. There's only one problem: rebuilding the nav mesh like this causes the game to freeze for several seconds when it's called.
How can I generate new terrain like this so that the enemies will path around it properly without freezing? Can I rebake the mesh asynchronously? One thing I tried was giving the wall prefabs Nav Mesh Obstacles, which removed the need to rebake the mesh, and the enemies do avoid the walls, but the enemies no longer take the most efficient route to the goal and tend to wander a bit. What's the best solution here? Thanks
Answer by gigos22 · May 02, 2021 at 05:02 AM
As far as I know, might be wrong, BuildNavMesh() cannot be natively async unless you make something up yourself, let's say sending it to a Task or a Thread. Either way, it is not recommended to my knowledge. But just like when working on Unity and baking the navmesh, you can't do anything while it is baking..
For this, the best solution is to prompt some kind of UI that says that the level is loading, thus it doesn't looks like it's freezing, it looks like it's the game being it's thing..
Secondly, if you see that it works better with walls being NavMeshSurfaces and not Obstacles - you should keep it that way.
For a game, it doesn't matter to it how it works.
Thanks for the tips. I had considered adding a "loading" between levels, but one of our core design plans was to make the level transition seamless, since for a short time both levels will be active at once (the defense objective falls through the floor then the player must do so soon after in order to keep defending). Since each level is flat, would it possible to optimize the mesh enough to speed up the bake to the point where it's not noticeable?
I've never thought about trying to achieve that.. Interesting.
Maybe try to tweak the voxel size of the bake..
If it is split into less voxels maybe it would take less time to bake.