How to make enemies randomly wander in a certain area of NavMesh?

Hey Guys,

So I’m currently making an open world game, and I want to make it so my enemies will roam around certain areas.

I have all my coding done for the enemies to attack my character if I move into a certain distance, but when I’m not in there radius I’ve currently just got them in a walk animation on the spot.

This is what I have so far…
using UnityEngine;
using UnityEngine.AI;

public class EnemyController : MonoBehaviour

    public float lookRadius = 10f;  

    Transform target; 
    NavMeshAgent agent; 
    CharacterCombat combat;

    private BaseEnemyAnimator baseEnemyAnimator;

    private float wanderSpeed = 2f;
    public float normalSpeed;
    public int roamRadius=70;

    void Start()
        target = PlayerManager.instance.player.transform;
        agent = GetComponent<NavMeshAgent>();
        combat = GetComponent<CharacterCombat>();
        normalSpeed = agent.speed;
        baseEnemyAnimator = GetComponent<BaseEnemyAnimator>();

    void Update()
        // Distance to the target
        float distance = Vector3.Distance(target.position, transform.position);

        //if not inside the lookRadius
        if (distance >= lookRadius)
            agent.speed = wanderSpeed;

        // If inside the lookRadius
        if (distance <= lookRadius)
                // Move towards the target
                agent.speed = normalSpeed;

                // If within attacking distance
                if (distance <= agent.stoppingDistance)
                    CharacterStats targetStats = target.GetComponent<CharacterStats>();
                    if (targetStats != null)

                    FaceTarget();   // Make sure to face towards the target

        // Rotate to face the target
        void FaceTarget()
            Vector3 direction = (target.position - transform.position).normalized;
            Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
            transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f);

        // Show the lookRadius in editor
        void OnDrawGizmosSelected()
            Gizmos.color =;
            Gizmos.DrawWireSphere(transform.position, lookRadius);


If anyone could help me figure out how to move them it would be greatly appreciated!

Happy Easter

If the world is big enough you could just pick a random position around them like new Vector3(transform.position.x + Random.Range(-x, x), 0, transform.position.y + Random.Range(-x, x)

If you want them to stay in a certain area you could parent them to an object with a box colider and use the bounds of it as max points for the next position. You can access the bounds.min and bound.max of the collider.