- Home /
I'm getting an index out of range error even though my arrays are filled with elements?
So in my game, I'm trying to randomly spawn objects with weighted probability and when I run the game, it gives me an "Array out of index range" exception. I've been trying for so long to get rid of this error, but I don't understand why this is happening.
I have 2 arrays that are both filled with elements (I checked myself) which are required. But when I check compare the lengths of the arrays, it says "False" even though I'm not changing them. Both arrays are filled with elements via the inspector.
It throws the error when I'm trying to instantiate the objects.
Essentially all trying to do is spawn objects randomly according to their probability weights in random locations.
Here is the code:
public GameObject[] fruits;
//Array of probability weights for each fruit
public int[] Weights;
IEnumerator Spawn ()
{
while(endGame == false)
{
Vector3 spawnPoint = new Vector3(Random.Range(-9, 9), 5, 0);
//This is to store the total sum of the weights each fruit has
int totalWeight = 0;
foreach(int weight in Weights)
{
//Adds each weight to calculate the total sum of the array
totalWeight += weight;
}
//Generate a random number between 0 and the sum of all weights
randomWeight = Random.Range(0, totalWeight);
foreach(int fruit in weights)
{
if (randomWeight < fruit)
{
//Instantiate the fruit from the value generated from randomWeight
//This instantiate line is what throws the error
Instantiate(fruits[randomWeight], spawnPoint, transform.rotation);
}
else
{
randomWeight -= weight;
}
}
Debug.Log("Size of weights AFTER loop " + weights.Length);
//Checks if both arrays are equal to each other
Debug.Log(fruits.Equals(Weights));
yield return new WaitForSeconds(1f);
Appreciate the help. Thanks
Answer by Hellium · Oct 02, 2019 at 04:51 PM
randomWeight = Random.Range(0, totalWeight);
for(int i = 0 ; i < Weights.Length ; ++i)
{
if (randomWeight < Weights[i])
{
//Instantiate the fruit from the value generated from randomWeight
Instantiate(fruits[i], spawnPoint, transform.rotation);
break; // Thanks Bonfire-Boy for the heads-up
}
else
{
randomWeight -= Weights[i];
}
}
And by the way Debug.Log(fruits.Equals(Weights));
does not compare the lengths of the array. You will always have false
in the console... If you want to compare the length, use Debug.Log(fruits.Length.Equals(Weights.Length));
(or more simply Debug.Log(fruits.Length == Weights.Length);
)
I think you also need to break out of the loop after instantiating.
Take the case where randomWeight comes out as zero... it'll be less than all the weights and they'll all get spawned.
(I realise this is something inherited from the OP btw)
Oh yes, you are totally right, fixed the code!
Oh and a by-the-by for the OP: separate arrays for fruits and weights is a really bad idea. Not only do you have to check they're the same length but also it's horrid for matching fruits with their weights in the inspector. In a situation like this it's very easy to do something along these lines:
[Serializable]
public class WeightedFruit
{
public GameObject fruit;
public int weight;
}
public WeightedFruit[] weightedFruits;
Thank you, it's working properly now! I can't believe all I had to do was change it to a for loop and put a break in. I also appreciate being shown how to make the code more efficient Bonfire-Boy so thanks for that too!
Answer by tormentoarmagedoom · Oct 02, 2019 at 04:42 PM
Hello there.
I did not read all your post, only the title.
But if you are getting an out of range error, is gecause of that, an index is out of the range.
if you have a array with 4 elements, and try to read the 5th element, will get that error, because the index can be up to 3 (remember 1st element is index=0). No other things to look for or find. Is just that.
Check carefull your code, debug it, and will see where is the error.
Good luck!
Your answer
![](https://koobas.hobune.stream/wayback/20220612212911im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
instantiate gameobject[] 1 Answer
Instantiate 1 at a time at each transform in array 1 Answer
How to spawn objects from CSV file 1 Answer
IndexOutOfRange error on iPhone, but not on PC/Player 0 Answers
Cannot find the length of an array 3 Answers