# NavMeshAgent.CalculatePath - how to use properly?

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) {
moving = true;
} else {
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?

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.
• 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? – Adariel Lzinski Feb 11 '15 at 14:15
• You sure you have a NavMeshAgent component on the same object? I suspect that's where your NullReferenceException is coming from. – MichaelHouse Feb 11 '15 at 14:18
• I fixed it. I had to add the path = new NavMeshPath` to the start function. Thanks! – Adariel Lzinski Feb 11 '15 at 14:18