How to set the length of what I think is an array.

New C# scripter here!!
I was wondering how I would change the length of a “”, or what I think is an array.
Heres my script

public Message[] text;
    public void ChangeText()
        text.Length = 100;

But, when I try this, I get the error:

 error CS0200: Property or indexer 'Array.Length' cannot be assigned to -- it is read only

Any help is appreciated.

Short answer: use the Array.resize() method – one dimensional arrays only.

Long answer: You cannot change the size of an array - it is immutable. But stick with me…

When you create an array, the .Net framework allocates a fixed sized space for it in a part of memory called the Heap. You cannot increase the size of that space. However, there is a useful static helper method Array.resize() which will create a new array and copy the contents of the old one across. So, you’re not changing the size of the original so much as creating a new one and “deleting” the old. However, the resize method only works for 1-dimensional arrays.

        int[] myInt = new int[10];
        Array.Resize(ref myInt, 20);

However, this is NOT something you want to do regularly, for example in every frame. The old space is not reusable and so repeated calls to resize can start to use up RAM, with the effect felt more so on old and mobile systems. A process called Garbage Collection will free this space at an undefined time but GC can cause glitches in your framerate.

Are arrays bad news? No. Feel free to use them but, if your data is likely to grow and you want to start out with a modest memory allocation, use Lists instead. They can be resized and, although they have a small overhead compared to Arrays (the system has to be more flexible in how it allocates memory), you shouldn’t worry about that.

Syntax is slightly different. Instead of int[] myArray = new int[10];, you write
List<int> myList = new List<int>(); Lists aren’t perfect either, though. Elements in an array are guaranteed to be in the order that you created them. A list is not guaranteed to be sorted, though that’s often not important. You add new elements to a List using myList.add(123);