- Home /
Resizing an array of gameObjects
Hi, everyone. I am attempting to make a mass component adder, but when I input the number of gameobjects and press update, it doesn't make the object fields. I know why, the array is at a length of zero, so how do I resize it? If necessary, here is my code so far. Any help would be appreciated =]
class MassComponentAdder extends EditorWindow { public var objs : GameObject[]; public var Int : int; public var script : MonoBehaviour; @MenuItem("CUSTOM/MassComponentAdder") static function Init() { var window = GetWindow(MassComponentAdder); window.Show(); } function OnGUI() { Int = EditorGUI.IntField(Rect(3, 3, position.width-6, 20), "Number of GameObjects: ", Int); if(GUI.Button(Rect(3, 25, position.width/2-6, 25), "Update")) { for(i = 0; i < Int; i++) { objs[i] = EditorGUI.ObjectField(Rect(3, 25+(i*25), position.width/2-6, 25), "Object "+i, objs[i], GameObject); } } if(GUI.Button(Rect(position.width/2, 25, position.width/2 - 6, 20), "Add Rigidbody")) { for(k = 0; k < Int; k++) { if(objs[k] != null) { objs[k].AddComponent(Rigidbody); } } } if(GUI.Button(Rect(position.width/2, 45, position.width/2 - 6, 20), "Add Light")) { for(j = 0; j < Int; j++) { if(objs[j] != null) { objs[j].AddComponent(Light); } } } if(GUI.Button(Rect(position.width/2, 65, position.width/2 - 6, 20), "Add Camera")) { for(l = 0; l < Int; l++) { if(objs[l] != null) { objs[l].AddComponent(Camera); } } }
}
}
Answer by efge · Apr 08, 2011 at 11:43 AM
Your GameObject array is a builtin array so you have to recreate the array and resize it before you assign individual elements:
objs = new GameObject[Int];
Answer by Proclyon · Apr 08, 2011 at 11:40 AM
resizing an array? You'd have to make a new one then. They have a fixed value.
Here's quote from a wiki post on the exception:
In programming, a variable-length array (or VLA) is an array data structure of automatic storage duration whose length is determined at run time (instead of at compile time).
Programming languages that support VLAs include Ada, APL, COBOL, Fortran 90, C (added in C99) and C# (as unsafe-mode stack-allocated arrays).
And you don't want to use the unsafe keyword unless you know ABSOLUTELY sure what you are doing and why (just like meddling with matrices internal library references and quaternions).
So basically , are you sure you want to do it that way? Consider other options!
Your answer
Follow this Question
Related Questions
Any way to invisibly tag an object? 1 Answer
Trigger an event from editor script? 0 Answers
SetReplacementShader in Editor Utility? 0 Answers
EditorApplication.update resetting 3 Answers