I’m using an A* script that i tried to integrate with multiple waypoints
problem is that my “TargetWaypoint” reaches the maximum length of the array and producing an index out of range.
Can anyone help me here?
here is the code
using UnityEngine;
using System.Collections;
using System;
//Note this line, if it is left out, the script won't know that the class 'Path' exists and it will throw compiler errors
//This line should always be present at the top of scripts which use pathfinding
using Pathfinding;
public class AstarAI : MonoBehaviour {
public Transform[] waypoint;
public Vector3 targetPosition;
private CharacterController controller;
Seeker seeker;
public Path path;
public float speed = 100;
private int currentWaypoint = 0;
public float nextWaypointDistance = 3;
public int TargetWaypoint = 0;
public void Start () {
targetPosition = waypoint[currentWaypoint].position;
//Get a reference to the Seeker component we added earlier
seeker = GetComponent<Seeker>();
controller = GetComponent<CharacterController>();
//Start a new path to the targetPosition, return the result to the OnPathComplete function
seeker.StartPath (transform.position,targetPosition, OnPathComplete);
}
public void OnPathComplete (Path p) {
Debug.Log ("Yey, we got a path back. Did it have an error? "+p.error);
if (!p.error) {
path = p;
//Reset the waypoint counter
currentWaypoint = 0;
}
}
public void FixedUpdate(){
if (path == null) {
//We have no path to move after yet
return;
}
if (currentWaypoint >= path.vectorPath.Count) {
Debug.Log ("End Of Path Reached");
if(currentWaypoint > waypoint.Length){
currentWaypoint = 0;
//seeker.StartPath (transform.position,waypoint[TargetWaypoint].position, OnPathComplete);
//AREA where problem occurs
if(TargetWaypoint < waypoint.Length){
TargetWaypoint++;
Debug.Log(waypoint.Length + " Waypoints");
}
else{
TargetWaypoint=0;
Debug.Log(waypoint.Length + " !!!Waypoints");
}
seeker.StartPath (transform.position,waypoint[TargetWaypoint].position, OnPathComplete);
}
return;
}
//Direction to the next waypoint
Vector3 dir = (path.vectorPath[currentWaypoint]-transform.position).normalized;
dir *= speed * Time.fixedDeltaTime;
controller.SimpleMove (dir);
//Check if we are close enough to the next waypoint
//If we are, proceed to follow the next waypoint
if (Vector3.Distance (transform.position,path.vectorPath[currentWaypoint]) < nextWaypointDistance) {
currentWaypoint++;
return;
}
}
}