How to resize an array without clearing it?

Whenever you call

arr = new Int[10]

It clears everything inside the array. For example, if I wanted to resize it later on, how would I avoid this?

You could try cloning the array to a new array of a different size.

Don’t use an array :slight_smile:

Javascript has Array which is resizeable. But your best bet is to import System.Collections.Generic and use a List;

I can’t tell if that code is Javascript or c#


var arr : List.<int> = new List.<int>(10);
arr[0] = 1;
arr[1] = 2;
arr.Insert(1,1000); // Array now contains 11 items - 1,1000,2 are the first 3

So it has the same semantics as an array, but it is resizable, sortable etc.

Lists are pretty fast, but here’s a trick if you won’t resize often, but you will use it often:

import System.Linq;

var arr : int[] = new int[100];

Do something that access the array a lot, then decide to resize it:

var work = arr.ToList();
//add stuff to work
work.Insert(20,2000); //example
arr = work.ToArray();

If you insist on using the built-in arrays, you can create a new array and copy the other array into it in a for loop.

public int[] array = new int[10];

void Start() {
    array = ResizeIntArray(array, 2);

public int[] ResizeIntArray(int[] array, int length) {
    int[] newArray = new int[length];

    if (length > array.Length) {
        for (int i = 0; i < array.Length; i++) {
            newArray _= array*;*_

} else if (length < array.Length) {
for (int i = 0; i < length; i++) {
newArray = array*;*

return newArray;

public bool myArray;
void OnValidate()
var tempArray = new bool[Random.Range(1, 10)];
for (int i = 0; i < myArray.Length && i < tempArray.Length; i++)
tempArray = myArray*;*
myArray = tempArray;