0
\$\begingroup\$

I am trying to randomly generate some values for a character using Javascript in Unity.

I have two arrays, one for colour, and one for body type. I want to get one value out of each array, randomly, which so far I have achieved like this:

var colours = new Array('red', 'green', 'blue');
var bodyTypes = new Array('thin', 'average', 'fat');

var colLen = colours.length;
var colour = colours[Random.Range(0,colLen)];

var bodLen = bodyTypes.length;
var bodyType = bodyTypes[Random.Range(0,bodLen)];

Debug.Log(colour);
Debug.Log(bodyType);

This works fine, however I would like to optimise it slightly, by putting the two arrays into another array and then using a loop to get each value. So far I have tried this:

var colours = new Array('red', 'green', 'blue');
var bodyTypes = new Array('thin', 'average', 'fat');

var arrays = new Array(colours, bodyTypes);

for(var array in arrays) {
    var arrayLen = Random.Range(0, array.length);

    Debug.Log(array[arrayLen]);
}

This gives the error "Length is non a member of Object". Is there any way of achieving what I want to do? I am very new to any type of game development, so I don't really know the best way to go about it.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Generally in javascript, you use for...in for objects. For arrays, you can use forEach. Like this:

var colours = new Array('red', 'green', 'blue');
var bodyTypes = new Array('thin', 'average', 'fat');
var arrays = new Array(colours, bodyTypes);

arrays.forEach(function(array, index,arrays) {
  var arrayLen = Random.Range(0, array.length);
  Debug.Log(array[arrayLen]);
})

...On a side note, I don't know if the new Array() constructor style is a Unity convention; if not, the typical JS way to define an array is just with [].

var colours = ['red', 'green', 'blue']
var bodyTypes = ['thin', 'average', 'fat'];
var arrays = [colours, bodyTypes];
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .