Search Unity

Question Experimental NavmeshSurface and OnPreUpdate

Discussion in 'Navigation' started by rob_vld, Mar 2, 2022.

  1. rob_vld

    rob_vld

    Joined:
    Jul 9, 2013
    Posts:
    191
    In the hierarchy i have:
    1 GameObject with a NavmeshSurface with prebaked mesh as child (navMesh)
    2 GameObjects with a script NPC attached

    With my game i am resetting the player's camera to V3.zero therefore requiring i also need to move the environment...
    also, because the terrain is too large to bake a navmesh, i came up with the following:

    I am moving the navmeshSurface under the NPC, during runtime, when it needs the navmesh to perform calculations... this works!... but not in the same frame.... there is some issue at hand, maybe something behind the scenes?

    Does anyone know how to solve this?
    Thanks

    (I wanted to add a simple image to support the above, but the server won't let me)

    Code (CSharp):
    1. public class NPC : MonoBehaviour
    2. {
    3.     public GameObject navmesh;
    4.     public NavMeshAgent navMeshAgent;
    5.     public GameObject target;
    6.  
    7.     private void Awake()
    8.     {
    9.         navMeshAgent = GetComponent<NavMeshAgent>();
    10.         NavMesh.onPreUpdate += SetNavmeshSurfacePosition;
    11.     }
    12.  
    13.     private void Update()
    14.     {
    15.         navmesh.transform.position = new Vector3(transform.position.x, 0f, transform.position.z);
    16.         if (navMeshAgent.isOnNavMesh == true)
    17.         {
    18.             navMeshAgent.SetDestination(target.transform.position);
    19.         }
    20.     }
    21.  
    22.     private void OnDestroy()
    23.     {
    24.         NavMesh.onPreUpdate -= SetNavmeshSurfacePosition;
    25.     }
    26.  
    27.     private void SetNavmeshSurfacePosition()
    28.     {
    29.         navmesh.transform.position = new Vector3(transform.position.x, 0f, transform.position.z);
    30.     }
    31. }
     
    Last edited: Mar 2, 2022