Search Unity

Question Is there a way to bake in runtime on instantiated prefab?

Discussion in 'Navigation' started by Kouseii, Jul 18, 2022.

  1. Kouseii

    Kouseii

    Joined:
    Jan 2, 2019
    Posts:
    9
    I'm instantiating the map and enemies as player goes on. Enemies using navmesh agent system so can I bake instantiated prefabs in runtime to use agent functions?
     
  2. Inxentas

    Inxentas

    Joined:
    Jan 15, 2020
    Posts:
    278
    I'm not 100% what you want to do with prefabs (I assume adding and removing them from play at runtime), but yes, you can (re)bake a NavMesh at runtime. But do keep in mind baking a mesh requires a ton of processing power as you'll bake the ENTIRE thing again and again. That's going to slow down your game a lot.

    If your map is large but static, it might be worthwhile to bake the whole thing beforehand and add NavMeshObstacles to the prefabs you want to (de)spawn over time. That way you won't have to rebake your entire game world and gameplay will remain smooth. I recommend you only bake at runtime when it's absolutely needed, and hide the FPS drop such an action requires behind a loading screen.
     
  3. palanolho_unity

    palanolho_unity

    Joined:
    Jun 20, 2022
    Posts:
    4
    I had a similar problem.
    If you try to build on the same frame as you instantiate the prefab, it will not be picked up by the rebuild.
    you can wither create a coroutine to bake with a 0.01 delay or enough to move to the next frame or you can use a flag to control when the prefab has been instantiated and on the UPDATE rebake if you are on the next frame (you can check frame with Time.framecount)