1
\$\begingroup\$

I am trying to have an object follow a path which basically is a square: the object moves to the next corner and pauses for some time. The movement is correct initially, however, after sometime it goes crazy and I have no clue why. The following shows what I am talking about:

  1. Correct movement phase.

enter image description here

  1. Beginning of deviations phase: the object is not following the square edges correctly.

enter image description here

  1. Crazy movements phase.

enter image description here

The function that does this is Patrol() in the following code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Game
{
    public class PatrollingEnemyBehaviour : EnemyBehaviour
    {
        public Vector3[] path;
        protected override void Update()
        {         
            base.Update();
            StartCoroutine(Patrol());            
        }

        private IEnumerator Patrol()
        {                      
            while (true)
            {
                if (m_TargetToShoot || m_Target)
                {
                    yield break;
                }
                foreach (Vector3 position in path)
                {
                    if (m_TargetToShoot || m_Target)
                    {
                        yield break;
                    }
                    Debug.Log("Going to: " + position);                    
                    m_NavMeshAgent.SetDestination(position);
                    yield return new WaitForSeconds(5);                    
                }   
            }            
        }
    }
}

The path is set within Unity editor to be the square.

The update function from the parent class deals with player detection and taking action.

Cheers.

\$\endgroup\$
2
  • \$\begingroup\$ What is your coroutine doing when you call it once from Start()? \$\endgroup\$ Commented Sep 29, 2021 at 7:27
  • \$\begingroup\$ I do not use it in Start(), solely in Update(). \$\endgroup\$ Commented Sep 29, 2021 at 8:41

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.