1
\$\begingroup\$

I seriously can't figure out how to use this function, and the documentation doesn't help at all.

Here's the documentation code:

public class ExampleClass : MonoBehaviour {
 public Transform target;
 private NavMeshAgent agent;
 void Start() {
     agent = GetComponent<NavMeshAgent>();
     NavMeshPath path;
     agent.CalculatePath(target.position, path);
     if (path.status == NavMeshPathStatus.PathPartial) {
     }
   }
}

Here's my code:

public class Movement : MonoBehaviour {
 NavMeshAgent agent;
 NavMeshPath path;

 void Start () {
     agent = GetComponent<NavMeshAgent>();
 }

 void MoveToTargetLocation() {
     agent.SetDestination(targetLocation); <-- being set somewhere else

     NavMeshPath path;
     agent.CalculatePath (targetLocation, path);

     if (path.status != NavMeshPathStatus.PathPartial) {
         if (Vector3.Distance (curLocation, targetLocation) > 0.55) {
             animation.CrossFade (animationRun.name);
             moving = true;
         } else {
             animation.CrossFade (animationIdle.name);
             moving = false;
         }
      }
   }
}

The error I'm receiving is:

Assets/Movement.cs(59,54): error CS0165: Use of unassigned local variable `path'

Am I supposed to be setting the path somewhere else?

\$\endgroup\$
1
\$\begingroup\$

Your problem is not with the NavMesh. You've defined path at two different scopes. Look at your code for two instances of NavMeshPath path; Try removing the local instance and add = new NavMeshPath(); to the other one.

I'm not sure why the documentation is the way it is. The method CalculatePath is clearly looking for an initialized NavMeshPath object. If it was to work as stated in their example, they'd need the out parameter option in the CalculatePath method to show that object will be initialized inside the method.

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ I fixed that. Still the same error. \$\endgroup\$ – Adariel Lzinski Feb 11 '15 at 14:07
  • \$\begingroup\$ @J.R. See update. \$\endgroup\$ – MichaelHouse Feb 11 '15 at 14:14
  • \$\begingroup\$ Now it gives me: NullReferenceException: Object reference not set to an instance of an object on line: agent.CalculatePath (targetLocation, path); So clearly I'm supposed to be setting the path variable somewhere? \$\endgroup\$ – Adariel Lzinski Feb 11 '15 at 14:15
  • \$\begingroup\$ You sure you have a NavMeshAgent component on the same object? I suspect that's where your NullReferenceException is coming from. \$\endgroup\$ – MichaelHouse Feb 11 '15 at 14:18
  • \$\begingroup\$ I fixed it. I had to add the path = new NavMeshPath to the start function. Thanks! \$\endgroup\$ – Adariel Lzinski Feb 11 '15 at 14:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.