0

I am making a game and trying to get the enemies patrol an area of waypoints. Currently each enemy has only 2 waypoints. When I start the game, I immediately get an IndexOutOfRangeException even though the array has been instantiated and the currentWaypoint variable is set to 0. Here is the code that I am currently using.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour {

    public GameObject[] Waypoints = new GameObject[2];
    public int CurrentWaypoint = 0;
    private GameObject Player;

    void Start () {
        Player = GameObject.Find ("Player");
        SetTarget (Waypoints[CurrentWaypoint]);  //Get IndexOutOfRangeException here
    }

    void Update () {
        GetComponent<Animator> ().SetFloat ("DistanceToPlayer", Vector3.Distance (transform.position, Player.transform.position));
    }

    public void SetTarget(GameObject target) {
        GetComponent<UnityEngine.AI.NavMeshAgent> ().SetDestination (target.transform.position);
    }

    public void IncrementWaypoint() {
        CurrentWaypoint++;
        if (CurrentWaypoint == Waypoints.Length)
            CurrentWaypoint = 0;
        SetTarget (Waypoints[CurrentWaypoint]);
    }
}

I don't understand why I am getting this error when, clearly, there are elements in the array.

ndsmith
  • 67
  • 1
  • 11

2 Answers2

0

you could try adding trycatch logic to your code

try{
    Player = GameObject.Find ("Player");
    SetTarget (Waypoints[CurrentWaypoint]); 
}
catch(Exception ex){
    //log the error somehow and/or set sensible defaults 
    //(i.e. logger.log("failed to set target, exception: " ex.Message, ex);
    SetTarget (Waypoints[0]); 
}

In general try catch logic is meant to help your code to run even when unexpected events happen (something triggers a weird waypoint), and by adding sensible logging in the catches you can tell where the problem lies more easily when something does happen.

also if it's possible, using coding editor like VS that lets you run in debug mode will also help a lot

The Lemon
  • 1,211
  • 15
  • 26
  • 1
    Just wanted to add that, yes, try-catch is for trapping errors, but they're more for errors that are outside of your control. In this case, OP is better off finding out why their data is unexpectedly null and fixing that problem. – Immersive Nov 06 '19 at 03:51
  • 1
    There are [four kinds of exceptions](https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/): **fatal**, which aren't your fault; **vexing**, which are the result of unfortunate design decisions; **exogenous** which are the result of untidy external realities impinging upon your beautiful, crisp program logic; and **boneheaded**, which are *your own darn fault,* you could have prevented them and *therefore they are bugs in your code.* The asker's exception is in the bonehead category and therefor should never be caught (fix your code!). – Draco18s no longer trusts SE Nov 06 '19 at 04:19
  • Just to add to the before comments: Also `SetTarget (Waypoints[0]); ` in your `catch` block can still produce exactly the same exception again in case there are no items in `Waypoints` at all ... – derHugo Nov 06 '19 at 06:09
  • was more just recommending the use of try catches, I'm aware my solution wasn't ironclad – The Lemon Nov 07 '19 at 03:33
0

I guess maybe your CurrentWaypoint in inspector window is not zero. Yes, you init the CurrentWaypoint in your code, but inspector window is going to set again. You should put

    CurrentWaypoint = 0    

in Start() function before

    SetTarget(Waypoints[CurrentWaypoint]);    
kaleidos
  • 1
  • 2