How to detect if object is off navmesh and how to place it back?

I have a companion character that follows the player around via NavMeshAgent. In one section, I am being shelled by artillery that effects the companion character if it hits close enough knocking them a few feet. Cool, but sometimes it knocks them off the NavMesh “out of bounds”. I would like to know:

  1. How to detect that this has happened?
  2. How to get them back on the NavMesh?

Otherwise they just run in place off the mesh trying to follow me

navMeshAgent.isOnNavMesh property tells you precisely that

Unity - Scripting API: AI.NavMeshAgent.isOnNavMesh

You can either make your agent remember it’s original position when it was knocked out or use NavMesh.SamplePosition to sample NavMesh to find a nearest point around when it wakes up

Unity - Scripting API: AI.NavMesh.SamplePosition

bool found = NavMesh.SamplePosition(point,out var sample,float.MaxValue,~0);

and move disabled NavMeshAgent to this sample.position (lets say by just lerping it back) and enable it once NavMesh point is reached successfully.