1
\$\begingroup\$

I want my enemy to move randomly to certain points on the scene. It moves to one point and then stops! It does not continue to the other points!

Here is my script:

using UnityEngine;
using System.Collections;

public class emove: MonoBehaviour {

NavMeshAgent ePath;
public GameObject[] POINT;

void Start () {
    ePath = GetComponent<NavMeshAgent>();
}

void Update () {

    foreach (GameObject waypoint in POINT) {
        ePath.SetDestination(waypoint.transform.position);
        ePath.speed = 2;

      // I write this, if you have different idea tell me please
        if (waypoint.activeSelf == false) // waypoint had it own script, when enemy touch any point it set off
        {
            ePath.SetDestination(waypoint.transform.position); // move to any other active waypoint.
            ePath.speed = 2;
        }
    }
}

What am I doing wrong?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ "is what i do is correct ?" If you see the expected behaviour on the screen, that's answered by a 'Yes'. So I guess you wouldn't be asking here, right :P \$\endgroup\$
    – Vaillancourt
    Commented Sep 29, 2016 at 20:24

1 Answer 1

2
\$\begingroup\$

The problem lies in your Update(). You are setting a new waypoint for your NavMeshAgent every frame, throwing in every point without evaluating if your NavMeshAgent has reached the previous waypoint.

using UnityEngine;
using System.Collections;

public class emove: MonoBehaviour {

NavMeshAgent ePath;
public GameObject[] waypoints;
int currentPointIndex;

void Start () {
    ePath = GetComponent<NavMeshAgent>();
    currentPointIndex = Random.Range(0, waypoints.Length - 1);
    //Start navigating to first *random* waypoint
    ePath = SetDestination(waypoints[currentPointIndex].transform.position);
    ePath.speed = 2;
}

void Update () {

    //reaching current waypoint
    if (Vector3.Distance(waypoints[currentPointIndex].transform.position,
            transform.position < 1) 
    {
        //Find next random waypoint
        currentPointIndex = Random.Range(0, waypoints.Length - 1);
        //Navigate to next waypoint 
        ePath.SetDestination(waypoints[currentPointIndex].transform.position);
    }
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .