- Home /
Array of Colors not working.
I'm trying to make a puzzle game where the tiles are generated with random colors at game start.
What I'm trying to do is create a Color[] array, store the eligible colors in it and then for every tile object choose a random color and change the mesh color to it.
For some reason though Unity keeps saying that the "array index is out of range".
Can someone tell me what dumb mistake am I making here?
var colors:Color[];
function Awake(){
colors[0]= Color.blue;
colors[1]= Color.red;
colors[2]= Color.green;
colors[3]= Color.yellow;
colors[4]= Color.cyan;
colors[5]= Color.magenta;
}
function Start () {
var colornum:int = Random.Range(0,3);
renderer.material.color = colors[colornum];
}
Am I creating the array wrong? I CAN do this creating a list and adding the colors to it, what I want is to understand why doing THIS way doesn't work. I already created the list and I'm gonna keep using that method anyway.
In C#, you have to create the array (in Awake): colors = new Color[6];
I thought javascript made the array for you, but I guess not (#pragma strict.)
But, it's often easier to make it public, then just enter colors in the Inspector.
Answer by Bunny83 · May 31, 2014 at 06:21 AM
Like Owen said you have to actually create the array. A native-array has a fix size which has to be specified when you create the array which you don't.
In Awake add this line infront of your others:
colors = new Color[6];
btw: In line 11 you select a random color but only from the first 3 colors, is that intentional? Usually you would do something like:
var colornum = Random.Range(0, colors.Length);
Answer by Eric5h5 · May 31, 2014 at 06:20 AM
Public variables take their values from the inspector, not your code. You should assign the size of the array and the colors in the inspector. If you want to do it in code, use private variables. Also use the length of the array in Random.Range, don't hard-code numbers.
Your answer
![](https://koobas.hobune.stream/wayback/20220613150316im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Changing two different objects renderer colour 1 Answer
How to Make Imported MagicaVoxel 3D Object Flash White 0 Answers
A node in a childnode? 1 Answer
Data overriding itself? 2 Answers