So I'm working in Unity 3D with UnityScript trying to make a cave generator using cellular-automata. Here is my problem, I've created two variables, width and height, and they need to be the size of my 2D array. I've also created a function to generate the map upon startup, so the array needs to be initialized upon startup. I know I need some kind of for
loop using .length
and one of the variables, but I'm not entirely sure how to do this. Any help would be great!
Asked
Active
Viewed 293 times
0

user3071284
- 6,955
- 6
- 43
- 57

Big_Guy
- 3
- 3
-
post your code and we will help – AlphaG33k Nov 05 '15 at 15:33
-
I've found it is often easier to use a 1D array and address it two-dimensionally (in JS, calculate the coords). – ssube Nov 05 '15 at 15:34
-
Changed references to JavaScript to UnityScript since that's what it technically is. http://wiki.unity3d.com/index.php/UnityScript_versus_JavaScript – user3071284 Nov 05 '15 at 16:05
2 Answers
0
If all of the rows in your 2D array are the same length you don't need to write a loop, simply check the length of an arbitrary row i.e
var arr = [
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
];
var height = arr.length; //4
var width = arr[0].length; //3
An example where you would need to loop through is if all of the widths were of differing lengths i.e
var arr = [
[1, 2, 3],
[1, 2, 3, 4]
];
var widths = [];
for (var i = 0; i < arr.length; i++) {
widths.push(arr[i].length);
}
console.log(widths); // [3, 4]
Here's how you generate a 2d array given the height and width
var height = 5,
width = 4;
var arr = [];
for (var i = 0; i < height; i++) {
arr[i] = [];
for (var j = 0; j < width; j++) {
arr[i][j] = "x";
}
}
console.log(arr);
// [ [ 'x', 'x', 'x', 'x' ],
// [ 'x', 'x', 'x', 'x' ],
// [ 'x', 'x', 'x', 'x' ],
// [ 'x', 'x', 'x', 'x' ],
// [ 'x', 'x', 'x', 'x' ] ]

Robert Corey
- 703
- 7
- 19
-
The length and width of the array are determined by variables so I don't think I can instantiate this array without using a loop. For example the length of my array could be anywhere from 10-100 depending on how the generation works out, so that variable would need to be the length of the array. After I have that I would need to make each value within the first array have an array within it with a size equal to the second variable. The length and height wouldn't even be known until after I run the code. That is why I think I need to make the array using a loop. Thanks for taking time to look! – Big_Guy Nov 05 '15 at 16:03
-
I edited my question to what I think answers your question. If that still doesn't help please post a sample of your code. – Robert Corey Nov 05 '15 at 16:19
-
0
Eh, in Unity you would just initialize them like this:
int gridSpace[,];
public int height;
public int width;
void Start()
{
gridSpace = new int[height,width];
MakeMapStuffHappen();
}
This will allow you to specify height and width in the editor (or programmatically)

Jesse Williams
- 653
- 7
- 21