Disclaimer: Yes, I do know that this is a somewhat common error, but in the way I’m doing it, I haven’t found a solution. I’ve had similar questions to this taken down, but as far as I know this error is unique. If this isn’t unique, feel free to take it down but please refer me to where I should look to find a solution to this.
I’ve been having issues with arrays for a while now. To keep it short, I’m trying to make a function that places a room, randomly places blocks, then places enemies on those blocks. The program then chooses one of the enemies in the array to hold a key.
In code, it’s along the lines of this:Check if should place a block. If block placed, check if should place an enemy. If should, instantiate enemy and place it in an array with all other enemies in the room. Once the room is finished generating, choose random placed enemy in array and change their variable hasKey to true.
I’ve been combing the forums for four hours, and all solutions are either out of date or don’t apply to my situation. As of right now, I’m getting the “index was outside the bounds of the array” error, but I know it’s because the length of the array is 0. What I don’t know is how to change the length of the array based on how many enemies are in the room. Setting the value too low results in the above error, but setting it too high results in blank slots and the chance that no enemy is picked.
Any ideas as to how to do this? I understand if it’s not possible with my current method, but I would ask that you steer me as to how to do this. Hopefully this post doesn’t come across as insensitive or redundant.
Code:
void generateCombatRoom()
{
Instantiate(baseRoom, new Vector2(roomPosX, roomPosY), transform.rotation);
startPosY = 3 / 2f;
startPosX = roomPosX - 19 / 2f;
int i = 0;
for (int j = 0; j < 20; j++)
{
randomChanceA = Random.Range(0, 2);
if (randomChanceA == 0)
{
Instantiate(brick, new Vector2(startPosX, startPosY), transform.rotation);
randomChanceB = Random.Range(0, 4);
if (randomChanceB == 0)
{
startPosY++;
enemies *= Instantiate(walkerEnemy[Random.Range(0, walkerEnemy.Length)], new Vector2(startPosX, startPosY), transform.rotation) as GameObject; //Placing the enemy*
Debug.Log(“Incrementing”);
i++;
startPosY–;
}
}
startPosX++;
}
int enemyWithKey = Random.Range(0, enemies.Length); //Picking an enemy to give a key
enemies[enemyWithKey].gameObject.GetComponent().dropsKey = true; //Giving it a key
startPosX += 4;
}
Any answers are appreciated, and thanks for hearing me out.
Thanks,
EpicCrownKing