Search Unity

Question NavMeshAgent.CalculatePath returns true on first frame, should return false

Discussion in 'Navigation' started by doodler345, Apr 23, 2023.

  1. doodler345

    doodler345

    Joined:
    Dec 30, 2021
    Posts:
    28
    Hello,

    I have a little problem regarding the NavMesh-Calculations.
    In my game theres an agent, who is trapped between dynamic carving obstacles, he should not be able to reach the target.
    In the Start()-function, NavMeshAgent.CalculatePath == NavMeshPathStatus.PathComplete, which should not be the case.
    I added a little time-buffer to recalculate the path after a certain amount of ms, it gives the right result than, but I already can feel thats bad practice.

    My guess is that the obstacle carving takes longer to calculate than the first frame.
    Is there anything I can do about that, like, is there a "WaitForCarvingToFinish" or something?

    Code (CSharp):
    1. public class NavMesh : MonoBehaviour
    2. {
    3.     [SerializeField] Transform target;
    4.     [SerializeField] NavMeshObstacle obstacle;
    5.     public NavMeshAgent navMeshAgent;
    6.  
    7.     NavMeshPath path;
    8.  
    9.     bool pathCheckedTwice;
    10.     float timer;
    11.  
    12.  
    13.     private void Start() {
    14.         path = new NavMeshPath();      
    15.         pathCheckedTwice = false;
    16.         timer = 0;
    17.         RecalculatePath();
    18.     }
    19.  
    20.     private void Update() {
    21.    
    22.  
    23.         //VERY BAD CODE! Waiting for dynamic obstacles to finish calculating before checking Path
    24.         timer += Time.deltaTime;
    25.         if(timer >= 0.05 && !pathCheckedTwice){
    26.             RecalculatePath();
    27.             pathCheckedTwice = true;
    28.         }
    29.  
    30.     }
    31.  
    32.     //gets called when mousebutton is released after dragging dynamic obstacle
    33.     public void RecalculatePath(){
    34.    
    35.         if (navMeshAgent.CalculatePath(target.position, path))
    36.         {      
    37.             if (path.status == NavMeshPathStatus.PathComplete){
    38.                 navMeshAgent.destination = target.position;
    39.                 navMeshAgent.isStopped = false;
    40.             }
    41.             else{
    42.                 navMeshAgent.isStopped = true;
    43.             }
    44.         }
    45.     }
    46. }
     
  2. Saniell

    Saniell

    Joined:
    Oct 24, 2015
    Posts:
    191
  3. doodler345

    doodler345

    Joined:
    Dec 30, 2021
    Posts:
    28