- Home /
How to resize c# array of gameobjects&
I have scripts using "c# array", so replacing evrything to "c# list" will be a headache. Help with code
------
if(MyUnits[MyUnits.length] != null){
Resize(MyUnits, (MyUnits.length) + 10);
}
------
public void Resize(GameObjectsArray, NewSize){
///WHAT GOES HERE????
}
It does not work for me
public static GameObject[] Test;
public void GroupResize (int Size, GameObject[] Group){
GameObject[] temp = new GameObject[Size];
for (c = 1; c < Group.Length;){
temp [c] = Group[c];
c = c + 1;
}
Group = temp;
void Start(){
Test = new GameObject[5];
Debug.Log (Test.Length);
GroupResize(15 ,Test);
Debug.Log (Test.Length);
}
Group has a local scope. You either need to pass by reference or return the results and assign it from your method return.
Can you please explain it in simple way or just paste the code. What and where i have to add to my code ??
Answer by Adamcbrz · Mar 16, 2014 at 03:15 PM
The list is you best option but to answer you question you will have to create a second array.
1) Create new array with new size.
2) Loop through old array and add each elements to new array.
3) set old array = to new array
$$anonymous$$odifying your code here is the results
public void GroupResize (int Size, ref GameObject[] Group)
{
GameObject[] temp = new GameObject[Size];
for (int c = 1; c < $$anonymous$$athf.$$anonymous$$in(Size, Group.Length); c++ ) {
temp [c] = Group [c];
}
Group = temp;
}
void Start ()
{
GameObject[] Test = new GameObject[5];
Debug.Log (Test.Length);
GroupResize (15, ref Test);
Debug.Log (Test.Length);
}
Good! It's the best Algorithm of resize in unity! Thank you, so much.
Uhm, System.Array.Resize does exactly this but probably a bit more efficient ^^. Also watch out, it seems there's a typo in the script because "c" should start at "0" and not "1". Otherwise you're skipping the first element.
Answer by Chronos-L · Mar 17, 2014 at 06:04 PM
Array.Resize doesn't actually resize an array as arrays have a constant size once created. The Resize helper method just creates a new array with the specified size and copies the elements from the old array into the new array.
When dealing with multidimensional arrays you have to do those steps your self.
To use Array.Resize you must include of using System with it , and if you use Random function inyour code you must now to add Unity.Random to it
Your answer
