- Home /
how to set an array length?
hello everyone, so i got the following arrays:
public GameObject[] planets;
public Vector3[] planetsPos;
they are part of a scritp that is supposed to spawn a random amount of planets around a sun, these guys wont work unless i manualy input their, size and since the value is random it becomes imposible. if someone knows how to set their length to the size of the planets (which would me stored in a variable) please tell me.
thanks a lot.
I'm a little confused, arrays are supposed to be of fixed size, soyou either set it to an upper bound that you know you won't pass, set it to the exact value, or use a list.
void Start(){
planets = new GameOject[100];
}
sorry, forgot to add the random number is only generated 1 time for the script to have that parameter to generate the planets in the system
Answer by SarperS · Nov 05, 2014 at 11:28 PM
You can either re-initialize the array like @Scribe mentioned. Or you can use the Array class's Resize static generic method.
Array.Resize(ref planets, newSize);
@Sarper-Soher Excellent... There are always surprises in this program$$anonymous$$g... LOL I suppose one can never know all the tools there are available. Used your example. Worked perfect. Thanks!!!
public Transform[] Look;
[SerializeField] public RaycastHit2D[] hit;
void Start() {
hit.Resize(ref Look, 1); //Not working :(
}
Okay, so I cannot seem to understand how to resize to another variable. plz help again lol
You are trying to resize the hit array to match the size of the look array I presume? Here you go
Array.Resize(ref look, hit.Length);
Resize is a static method of the .net Array class thus you can't access it through an instance. First parameter is the array to resize passed by reference, the Resize method will create a new array of the requested size and copy your array into it using Array.Copy and set your reference array back into this new array.
Second parameter is the new size, here we're just passing the size of your second array. Below is the .net doc link, read it for more details.
https://docs.microsoft.com/en-us/dotnet/api/system.array.resize?view=netframework-4.7.1#System_Array_Resize__1___0____System_Int32_
btw You don't need to use the attribute SerializeField on public variables, they are already serialized.
Your answer
![](https://koobas.hobune.stream/wayback/20220613170821im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Array - 'transform' is not member of Object 1 Answer
Tree size problem when using terrain tool 0 Answers
Parsing XML - appropriate array size 3 Answers
System.Array.IndexOf 1 Answer