- Home /
Using a for loop to generate and populate an array
My end goal is to create a function that takes an integer value and passes it to an array as its length. I need the array to then generate to that length and populate itself with integer value that increment as the position of the array increments. However, with the code I've come up with, the array generates to the length without fail. The problem is that it only assigns the last value the value that I need it to. For example if the array had a length of 25, the first 24 elements will all have a value of 0 and only the 25th element would contain a value of 25. Any help in generating this array would be greatly appreciated. Thank you.
using UnityEngine; using System.Collections;
public class ShipGenerator : MonoBehaviour { public int amountOfClasses; public int[] classAmount;
void Start()
{
shipClasses (amountOfClasses);
}
void shipClasses(int numberOfClasses)
{
for(int i=0; i < numberOfClasses; i++)
{
classAmount = new int[numberOfClasses];
classAmount[i] = i + 1;
}
}
}
Below is an example of what I hope to accomplish without having to type out the array myself as I want it to be dynamic. /* public int[] classNumber;
void Start()
{
classBuild();
}
void classBuild()
{
classNumber = new int[3];
classNumber[0] = 1;
classNumber[1] = 2;
classNumber[2] = 3;
...
}
*/
Answer by GameVortex · Jan 12, 2015 at 11:38 AM
When you are looping through and generating your array, you are creating a new array object in each iteration (at line 10):
classAmount = new int[numberOfClasses];
So everytime you set the value you are also creating the array again which initializes all values to 0, and then you set the last value.
The solution is to move the initialization of the array outside of the for loop before it begins, and only assign the values in the loop.
Your answer
![](https://koobas.hobune.stream/wayback/20220613180209im_/https://answers.unity.com/themes/thub/images/avi.jpg)