- Home /
Check amount of elements in array
Hello,
In my script I have 3 options, the arrays contains 1, 2 or 3 elements (colors) Is there a way to check the amount of elements in the array? I don't mean the lenght of the array, I mean the amount of elements in the array. I do this to use it in a switch statement.
public var colorArray = new Color[3];
Function Update()
{
switch(// amount of variables in the array)
{
case 1 :
// action 1
break;
case 2 :
// action 2
break;
case 3 :
// action 3
break;
}
}
Answer by Peter G · Nov 27, 2011 at 05:12 PM
With a value type such as Color, the number of elements should equal the length of an array.
For reference types you can have nulls, but with a value such as Color, there should be as many elements as the length of the array.
Ok thanks, but if I declare the lenght from the beginning like I did in this script, the length isn't equal to the amount of elements in the array. Or am I wrong? Thank you for your help
Ok, this is going to annoy you, but it has to do with the serialization. Value types (that aren't specifically marked nullable) can never have a null value. Every element in your array has a value. Its whatever the default is for your value type and in the case of colors, its Color.black
.
What's actually happening is Unity simply isn't changing the length of your array like you told it to. This has to do with the public
variable serialization. Unity serializes your public arrays so that it can display them in the inspector properly. Unity isn't reading the value you wrote in the script any more, its reading the value its stored from the inspector so it won't change anything if you modify the variables default value in the script.
Two easy ways of fixing it.
$$anonymous$$ake the array private. Unity only serializes public vars for the inspector so private variables are unaffected.
Recreate the array in the start function with the proper length.
Answer by ptdnet · Nov 27, 2011 at 05:24 PM
int HowManyElementsAreInMyArray(object[] a) {
int ohyeahbaby = 0;
for (x = 0; x < a.GetUpperBounds[0]; x++) { // might have mispelled that
if (a[x] != null) ohyeahbaby++;
}
return ohyeahbaby;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613055139im_/https://answers.unity.com/themes/thub/images/avi.jpg)