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