- Home /
Array.length edited using scripts
hi my friends , i have little problem regarding arrays , i have any array that returns some game objects
function Awake(){
var goh = GameObject.FindGameObjectsWithTag("Hanger");
Hangers = goh;
}
it works fine and it returns about 12 GameObject, i want an another variable (INT) to change the length of this array on the fly , and removes the objects also from the Array.
i tried doing this:
function Start(){
Hangers.Length = Fightercount;
}
but i get this error:
Assets/Carrierscripts/LaunchFighter.js(32,9): BCE0053: Property 'System.Array.Length' is read only.
is there a workaround for this problem, thx in adv.
Answer by Eric5h5 · Dec 02, 2011 at 10:07 AM
As the error says, the length is read-only. You can't change the length of arrays. If you need to add/remove objects from an array, use List (with Add and Remove) instead of arrays:
import System.Collections.Generic;
function Awake(){
var goList = new List.<GameObject>(GameObject.FindGameObjectsWithTag("Hanger"));
}
By the way, there's no point doing this:
var goh = GameObject.FindGameObjectsWithTag("Hanger");
Hangers = goh;
You can just do this:
Hangers = GameObject.FindGameObjectsWithTag("Hanger");
Although you should use lowercase for variable names.
thx for fast respond , wt i wanted to do is : i have a carrier that have many hangers , i decide how many fighters i want to launch then it uses this many hangers depending of the count of fighters , wt do u suggest to do ins$$anonymous$$d of arrays??
and again thx for any help.
Answer by StephanK · Dec 02, 2011 at 09:59 AM
You can't change the length of an array once it's setup. If you want to remove objects from an array you will have to make a new one with the correct length and assign the objects that you want to keep from your original array to the new one.
On another note it seems odd to look for already existent objects in a scene and then only use a few of them. If you don't need them, why create them in the first place?
Stephan, this works System.Array.Resize.(arrayname, 10);