NavMeshAgent: Keep Enemy x Distance from Player?

I have an enemy archer controlled via NavMesh & Mecanim. The enemy is set to “See” the player from 24 units away, and then approach, but at 20 units, via NavMesh stopping distance, stop. This works. The enemy then shoots an arrow, via scripting and Mecanim.

However, if the player gets too close, say, 15 units, I want the enemy to move back, attempting to keep at least 15 units between him and the player object.

I also want to make sure the enemy doesn’t move out of visual range of the player, since he needs to see the player in order to fire the arrow – so I wouldn’t want the enemy to move behind a wall or something.

How would I go about doing this?

In Update(), check the distance to the player. If the player is too close, raycast back (in the opposite direction from the player) to the archer’s desired distance. If it’s clear, just set your NavMeshAgent’s destination to that point. If the raycast hits something, keep trying 10 degrees further out on either side until you find a clear spot.

You can get a lot fancier than this, incorporating map analysis and more advanced AI, but the approach above should give you pretty good behavior already.