0
\$\begingroup\$

I have a character moving along 5 waypoints and it should be looping, but for some reason the Update method stops after the character reaches the last waypoint. The output for currWaypoint is 0, 1, 2, 3, 4, 5, 0, and then it stops updating.

EDIT: after further debugging, I found out that the remaining distance for that last iteration never hit zero and keeps hovering at the 0.5 range.

private Animator anim;
private UnityEngine.AI.NavMeshAgent agent;
public GameObject[] waypoints;
int currWaypoint;

void Awake()
{

    anim = GetComponent<Animator>();

    if (anim == null)
        Debug.Log("Animator could not be found");

    agent = GetComponent<UnityEngine.AI.NavMeshAgent>();

    if (agent == null)
        Debug.Log("NavMeshAgent could not be found");
}

void Start() {
    currWaypoint = 0;
    Debug.Log("let's go!");
    setNextWaypoint();
}

void Update() {
    if (agent.remainingDistance == 0 && !agent.pathPending) {
        Debug.Log("turn" + currWaypoint);
        setNextWaypoint();
    }
}

private void setNextWaypoint() {
    if (waypoints.Length == 0) {
        Debug.LogError("waypoints must exist for character to move");
    }
    if (currWaypoint < waypoints.Length) {
        Debug.Log(currWaypoint);
        agent.SetDestination(waypoints[currWaypoint].transform.position);
        currWaypoint++;
        Debug.Log("new: " + currWaypoint);
    } else {
        currWaypoint = 0;
    }
}
\$\endgroup\$
2
  • 4
    \$\begingroup\$ agent.remainingDistance == 0 can cause some issues because comparing strict against 0 might never reach it. Usually you allow a slight error margin. \$\endgroup\$
    – Zibelas
    Feb 22 at 7:13
  • \$\begingroup\$ this works! thank you :D \$\endgroup\$ Feb 29 at 5:12

0

You must log in to answer this question.

Browse other questions tagged .