Quantcast
Channel: Questions in topic: "loops"
Viewing all articles
Browse latest Browse all 184

Using a for loop to generate and populate an array

$
0
0
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; ... } */

Viewing all articles
Browse latest Browse all 184

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>