So I have a script set up for my enemy to walk to a set of way points on the map I have set up through an array. I keep getting the error that the array index is out of bounds which I don’t quite understand why. I would like for him to cycle through the way points in order back and forth but it only goes to the third way point then the error screen appears. Any help is greatly appreciated thank you!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public float speed1 = 3.0f;
public float speed2 = 3.0f;
public GameObject[] waypoints;
private int waypointnum = 0;
public float near = 5f;
public GameObject player;
private Rigidbody2D rb;
private bool chase = false;
private bool chaseend = false;
private Vector2 Target { get { return player.transform.position; } }
private Vector2 Position
{
get
{
return transform.position;
}
set
{
transform.position = value;
}
}
private void Start()
{
rb = GetComponent<Rigidbody2D>();
Position = waypoints[0].transform.position;
}
//SHOULD RESET POSITION AFTER CERTAIN AMOUNT OF TIME.
//IF spotted speed should increase and decrease when reset.
private void ChaseChar()
{
float dist = Vector2.Distance(Position, Target);
if (dist < near)
{
float step = speed2 * Time.fixedDeltaTime;
Position = Vector2.MoveTowards(Position, Target, step);
rb.MovePosition(Position);
}
}
private void FixedUpdate()
{
float dist = Vector2.Distance(Position, Target);
waypointIndicator();
if (dist < near)
{
chase = true;
}
else if(chase == true)
{
chase = false;
chaseend = true;
}
else
{
float step = speed2 * Time.fixedDeltaTime;
Position = Vector2.MoveTowards(Position, waypoints[waypointnum].transform.position, step);
rb.MovePosition(Position);
}
if (chase == true)//HAS BEGUN CHASING, CHASES
{
ChaseChar();
}
else if (chaseend == true)
{
////After time limit will reset back to original position.
}
}
public void waypointIndicator()
{
//if increasing then add one to waypoint each time until reaching position
// else if decreasing do same
bool adding = true;
bool subbing = false;
bool moving = true;
if(Position == new Vector2(waypoints[waypointnum].transform.position.x, waypoints[waypointnum].transform.position.y))
{
moving = false;
}
else { moving = true; }
if (!moving)
{
if (adding)
{
if (waypointnum < waypoints.Length-1)
{
waypointnum++;
}
else
{
waypointnum++;
adding = false;
subbing = true;
}
}
else if (subbing)
{
if (waypointnum > 0)
{
waypointnum--;
}
else
{
waypointnum--;
adding = true;
subbing = false;
}
}
}
}
}