So I was following a tutorial on you tube, and everything works fine until I restart the game, my restart function is simply load a new scene(which is the current one) t, problem occurs on one array that somehow is out of range, I tried reseting the index changing the length but nothing,
Here is the code for now :
This is the script where the array is , its a group of waypoints
using UnityEngine;
public class Waypoints : MonoBehaviour {
public static Transform[] points;
void Awake()
{
points = new Transform[transform.childCount];
for (int i=0;i<points.Length;i++)
{
points*=transform.GetChild(i);*
}
}
}
Second script that define enemy movement
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(EnemyScript))]
public class EnemyMovement : MonoBehaviour {
private Transform target;
private int wavepointIndex;
private EnemyScript enemy;
void Start()
{
wavepointIndex = 0;
target = Waypoints.points[0];
enemy = GetComponent();
}
void Update()
{
Vector3 dir = target.position - transform.position;
transform.Translate(dir.normalized * enemy.speed * Time.deltaTime, Space.World);
if (Vector3.Distance(transform.position, target.position) <= 0.4f)
{
getNextWaypoint();
}
enemy.speed = enemy.startSpeed;
}
void getNextWaypoint()
{
if (wavepointIndex >= Waypoints.points.Length - 1)
{
endPath();
return;
}
wavepointIndex++;
target = Waypoints.points[wavepointIndex];
}
void endPath()
{
PlayerStats.Lives–;
Destroy(gameObject);
}
}
I guess that the problem is that every time i restart the game it does not load that array of waypoints so it can give me a path.
The error occures in line 17 of the second script which is bolded in the script
target = Waypoints.points[0];
error: IndexOutOfRangeException: Array index is out of range.
EnemyMovement.Start () (at Assets/EnemyMovement.cs:17)
`