How to transform arrays into easier to edit list (JS)

I want to use this code to run gui elements and when arrows spawn/despawn in the game.

class StageEditor {
	var story: String;
	var controlArray: String[];
	var taskName: String[];
	var taskStatus: Texture2D[];
	var PC: boolean;
	var arrowArray: GameObject[];
}

var stage : StageEditor[];

The problem is if i want to add or change any of the stages its a ton of work going through and changing each element in multiple arrays. I think an easier way to do this would be to put this in a list but idk how to do that. Or if theres an even better way to go about making this easier to add/subtract/change stages in the middle then using a list i’d love to hear it!

Everything you need about lists, arrays, etc in JS or C# is here.

Couple of notes:

  • Do your best avoiding ArrayList,
    use a generic List instead.
  • Whenever you have the chance to use
    an array instead of a list, do it.

Here’s how you declare a list in JS:

var myList : List.<myType> = new List.<myType>();

Short summary of what you could do with it now:

myList.Add(element);             // adds it to the end of the list
myList.Insert(atIndex, element); // inserts 'element' at 'atIndex'
myList.Remove(element);          // finds 'element', and removes it from the list
myList.RemoveAt(index);          // removes the element at 'index'
myList.Clear();                  // removes all elements
myList.Contains(element);        // returns true if 'element' is inside myList
myList.Sort();                   // sorts the list elements
myList.Count                     // returns how many elements inside the list

Of course, when you add, remove, insert etc all memory allocations/de-allocations are done for you.

It sounds like your problem is more to do with removing/moving stages around your array than the use of an array/list.

I believe what you are looking for is “custom inspector” classes. Basically you can write code that will replace/append the inspector view. For example, you could write a button that will delete a stage then do the tidy up for you. If you look at the documentation it should get you started.

You will basically want to do something along the lines of for(int i = 0; i < stage.Length; i++) { if(GUILayout.Button("Remove")) RemoveLogic(i); }. As others have mentioned, actually implementing the logic will be easier if you use a List, since it comes pre-bundled with Remove and Insert logic.

On an unrelated note, it is good practice to give arrays plural names. Eg: stages, taskNames, etc. This lets you make nice easy to read for-loops with foreach(taskName in taskNames) {}. Note that you can’t edit a list while you are foreach-ing over it though

Take a look at:

http://wiki.unity3d.com/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use%3F

As pointed out in:

http://answers.unity3d.com/questions/165975/javascript-list.html