Hi everyone, I did a script. Basically, it must allow AI(enemy) to follow a path through waypoint system but when I start the game, I have the error, Array out of range. I know what this mean but I don’t know how to resolve it. If someone can help me
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EiMovement : MonoBehaviour {
public static Transform[] wayPoints;
private Transform target;
public float speed;
private int wayPointIndex;
// Use this for initialization
void Awake () {
wayPoints = new Transform[transform.childCount];
for (int i = 0; i < wayPoints.Length; i++) {
wayPoints[i] = transform.GetChild (i);
}
}
void Start(){
target = wayPoints[0];
}
// Update is called once per frame
void Update () {
Vector3 dir = target.position - transform.position;
transform.Translate (dir.normalized * speed * Time.deltaTime);
if (Vector3.Distance(transform.position, target.position) <= 0.2f){
goNextWayPoint ();
}
}
void goNextWayPoint(){
if (wayPointIndex == wayPoints.Length -1) {
Destroy (gameObject);
return;
}
wayPointIndex++;
target = wayPoints[wayPointIndex];
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WaypointInisalize : MonoBehaviour {
public static Transform[] wayPoints;
// Use this for initialization
void Start () {
wayPoints = new Transform[transform.childCount];
for (int i = 0; i < wayPoints.Length; i++) {
wayPoints[i] = transform.GetChild (i);
}
}
// Update is called once per frame
void Update () {
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EiMovement : MonoBehaviour {
private Transform target;
public float speed;
private int wayPointIndex = 0;
// Use this for initialization
void Awake () {
}
void Start(){
target = WaypointInisalize.wayPoints[0];
}
// Update is called once per frame
void Update () {
Vector3 dir = target.position - transform.position;
transform.Translate (dir.normalized * speed * Time.deltaTime);
if (Vector3.Distance(transform.position, target.position) <= 0.2f){
goNextWayPoint ();
}
}
void goNextWayPoint(){
wayPointIndex++;
target = WaypointInisalize.wayPoints[wayPointIndex];
/*if (wayPointIndex == wayPoints.Length - 1) {
target = wayPoints[wayPointIndex];
wayPointIndex++;
//Destroy (gameObject);
//return;
}
wayPointIndex++;
target = wayPoints[wayPointIndex];*/
}
}