-7

What exactly does "Index was outside the bounds of the array" mean? I'm trying to program in an enemy moving in a C# 2d game in unity and this message pops up in the console as soon as it hits a wall

I've tried increasing the capsule collider of my enemy, but that only makes it hit the wall faster and the message pop up sooner. I've also tried increasing the Box Collider 2d, but the same result occurs.

Vector2 previousDirection;

Vector2 GetRandomDirection()
{
    Vector2[] directions = { Vector2.up, Vector2.right, Vector2.down, Vector2.left };

    Vector2[] availableDirections = new Vector2[directions.Length - 1];
    int index = 0;
    for (int i = 0; i < directions.Length; i++)
    {
        if (directions[i] != previousDirection)
        {
            availableDirections[index] = directions[i];
            index++;
        }
    }

    int randomIndex = Random.Range(0, availableDirections.Length);

    Vector2 randomDirection = availableDirections[randomIndex];

    previousDirection = randomDirection;

    return randomDirection;
}

I'm pretty sure this is the culprit because after I added this section, the message started appearing

1 Answers1

0

I think your problem is here:

Vector2[] availableDirections = new Vector2[directions.Length - 1];

You're defining the size of Vector2 one item too small

Try using

Vector2[] availableDirections = new Vector2[directions.Length];

Index out of bounds means you're trying to access an item outside of its defined size.

The size of availableDirections is 3 so you can index it from [0] to [2]. Since you increment index in your for loop (which goes from 0 to 3) without checking it, it will become 3 eventually and availableDirection[3] is not defined and thus you get "Index was outside the bounds of the array".

Edit: You might try this (not tested, I don't have Unity installed):

List<Vector2> availableDirections = new List<Vector2>() { Vector2.up, Vector2.right, Vector2.down, Vector2.left };
availableDirections.RemoveAt(available.IndexOf(previousDirection));
previousDirection = availableDirections[new Random().Next(availableDirections.Length - 1)];
return previousDirection;
esp
  • 19
  • 1
  • 5
  • Thank you, the error no longer pops up but the desired outcome has not worked yet. I am trying to ensure that my enemy doesn't go in the same direction twice in a row, and yet it still does. What should I change about my code so that it works? If there's nothing wrong with my code then it could be a separate issue with the enemy stopping movement after hitting a wall. – Andy Ries May 18 '23 at 18:11
  • Thats an entirely different issue – BugFinder May 18 '23 at 18:30