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 Answer 1

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.

\$\endgroup\$
5
  • \$\begingroup\$ I fixed that. Still the same error. \$\endgroup\$ Feb 11, 2015 at 14:07
  • \$\begingroup\$ @J.R. See update. \$\endgroup\$
    – House
    Feb 11, 2015 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\$ Feb 11, 2015 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\$
    – House
    Feb 11, 2015 at 14:18
  • \$\begingroup\$ I fixed it. I had to add the path = new NavMeshPath to the start function. Thanks! \$\endgroup\$ Feb 11, 2015 at 14:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .