- Home /
Array out of range
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];
}
}
Sorry for language
Comment
Answer by BigBrotherParties · Aug 04, 2017 at 08:56 PM
I solved the problem at 50%, I put the target Transform on public state, so I can assign the waypoint prefab, now the only problem that I have is "Array out of range"