For all the time I have been using Unity I always resized arrays using the Inspector, and never learned how to do it in script, because every time I had to I would simply use a list instead.
However, this time I don’t want to use lists because I don’t feel the need to, since the array is only resized once.
I simply want to make an array the same size as another array that had been set in inspector.
How would I do that in code without having to mark my arrays as public?
If you want the size of the array to be initialized by a pre-set number of elements:
//New int array with 5 elements.
int[] array = new int[] { 1, 2, 3, 4, 5 };
If you want to set the size of the array to a specific value with no pre-set elements:
//New int array with a capacity of 5 elements.
//Each element is initialized to their default value.
int[] array = new int[5];
For your specific case:
public class Example : MonoBehaviour
{
public int[] mySerializedArray;
int[] myOtherArray;
void Awake()
{
myOtherArray = new int[mySerializedArray.Length];
}
}
public class Example : MonoBehaviour
{
public int[] mySerializedArray;
int[] myOtherArray;
void Awake()
{
myOtherArray = new int[mySerializedArray.Length];
}
}
It initializes the length of one array with the length of another array.
You can’t do this, if that’s what you were wondering…
public class Example : MonoBehaviour
{
public int[] mySerializedArray;
int[] myOtherArray = new int[mySerializedArray.Length];
}
…Since the fields have not yet been initialized. It has to be done in a constructor or method.