Enemy AI patrol WaitForSeconds problem

Hi everyone. I am trying to make a simpe Enemy AI patrol system (which works)

The problem is here, that i want my player to stop WaitForSeconds(3); and afterwards go to the new point and so on, but my coding doesn’t seem to work

All help is appreciated

Here is the code:

using UnityEngine;
using System.Collections;

public class EnemyPatrol : MonoBehaviour {

    public Transform[] patrolPoints;
    public float moveSpeed;
    private int currentPointPosition;


    // Use this for initialization
    void Start () {
        transform.position = patrolPoints[0].position;
        currentPointPosition = 0;
    }
   
    // Update is called once per frame
    void Update () {

        if (transform.position == patrolPoints[currentPointPosition].position)
        {
            currentPointPosition++;
        }

        if (currentPointPosition >= patrolPoints.Length)
        {
            currentPointPosition = 0;
        }

        transform.position = Vector3.MoveTowards(transform.position, patrolPoints[currentPointPosition].position, moveSpeed * Time.deltaTime);
    }
}

I was thinking about putting the Couroutine before the CurrenPointPosition++;, but that doesn’t work either

Hi, Update() runs every frame and can’t be a coroutine which would be needed to yield and wait 3s.

Try to store time of next movement in a variable, something like:

float _nextMoveTime;
bool _isMoving = true;

void Update()
{
        if (this._isMoving)
        {
            if (transform.position == patrolPoints[currentPointPosition].position) //you should consider replacing this with Vector3.Distance() < 0.01f or such to avoid issues from floating precision
            {
                currentPointPosition++;
                if (currentPointPosition >= patrolPoints.Length)
                {
                     currentPointPosition = 0;
                }

                //Initiate a delay before moving again
                this._isMoving = false;
                this._nextMoveTime = Time.time + 3;
           }
           else
           {
                transform.position = Vector3.MoveTowards(transform.position, patrolPoints[currentPointPosition].position, moveSpeed * Time.deltaTime)
           }
        }
        //When not moving, check if delay is over
        else if (this._nextMoveTime < Time.time)
        {
            this._isMoving = true;
        }
}

Oh god. Thank you so much. Now everything seems to make sense! :slight_smile:

1 Like