I am using Unity NavMesh to control my units.

I am running into an Issue when updating Navmesh at runtime, It seems agents re-calculate their path whenever it is modified, which makes sense, but it causes this line (check if unit is on last corner) to return an IndexOutOfBounds error:

agent.steeringTarget == agent.path.corners[agent.path.corners.Length - 1]

I guess something is happening while re-calculating path that might mess with this for 1 frame. I solved this by putting a try/catch around it, but is there some better way I can manage this so I don't get the error at all?

  • \$\begingroup\$ Have you considered checking whether the agent has a valid path, or has a path with more than 0 corners, before assigning the steering target? \$\endgroup\$ – DMGregory Jul 10 '20 at 18:21
  • \$\begingroup\$ Is that supposed to be a single = instead of a ==? \$\endgroup\$ – Kevin Jul 10 '20 at 18:21
  • \$\begingroup\$ @DMGregory Yeah I mostly posted here to see if someone had a better idea, but seems this is the way to go! \$\endgroup\$ – Majs Jul 11 '20 at 12:32
  • \$\begingroup\$ We might have a better solution if you show us more of your code. But when you show us only one line, about the only solution we have is "don't run that line in exceptional conditions". With a better view of the context, we might be able to suggest ways to avoid the exceptional condition reaching this point in the first place. \$\endgroup\$ – DMGregory Jul 11 '20 at 12:33

The most likely explanation is that the path length is 0, so agent.path.corners.Length - 1 would give an index of -1, which is of course invalid.

Try this:

if (agent.path.corners.Length > 0) {
    agent.steeringTarget = agent.path.corners[agent.path.corners.Length - 1]

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.