Query with C# arrays and List<>

Hi,

Strange question, but I’m new to C# and I’m trying to differentiate between the two blocks of code.

So, this:

public List<Color>	shapeColor		= new List<Color>();

if(shapeColor.Count > 0)
		{
			int newColor = Random.Range(0, shapeColor.Count);
			renderer.material.color = shapeColor[newColor];	
		}

And this:

public Color[]		shapeColor;

if(shapeColor.Length > 0)
		{
			int newColor = Random.Range(0, shapeColor.Length);
			renderer.material.color = shapeColor[newColor];	
		}

Both blocks seem to achieve the same thing - selecting a random colour from an array of colours selected in the inspector. My understanding of C# was that you should use List<> if the array of items you’re using is not a set length as it will produce errors otherwise. Here, the colours are picked in the Inspector window, so it can’t be defined in the code.

I had initially defined the shapeColor array as below:

public Color shapeColor[];

But ran into errors with the rest of the code because of the above. My question is, how is using Color any different and is could this cause any difficulties?

Native arrays “” are not resizable at run time. Lists are. You should use native arrays if the contents will not change during the execution of the game and Lists otherwise. They are semantically similar but arrays use Length and Lists use Count for the number of items.

array is just a bunch of memory in a row. So it’s super-fast to access and super-slow to resize (can’t be resized, you have to grab a new chunk of memory and copy the values over).

List is a class which essentially contains a array and helper functions to make resizing it less prone to error.

There are no errors for using variable-length arrays, you just have to be aware that you’re using variable-length arrays.