Concatenating to a String[] Array Dynamically

The task is to dynamically create a String of arbitrary length and add strings to it. It needs to be passed to the 3rd argument of GUI.Toolbar which takes a String. I have tried the following declarations:


var toolbarStrings:String[]=[""];

var toolbarStrings:String[]=[];

var toolbarStrings:String[];

var toolbarStrings:String=[];

var toolbarStrings=[""];

var toolbarStrings=new Array();

var toolbarStrings=new Array(String);

To each of these I have attempted the following initialization in Awake():


for(var i:int=0;i<=5;i++)toolbarStrings.push("Number "+i);

for(var i:int=0;i<=5;i++)toolbarStrings*=new String("Number "+i);*
_for(var i:int=0;i<=5;i++)toolbarStrings*="Number "+i;*_
_*for(var i:int=0;i<=5;i++)toolbarStrings[toolbarStrings.length]="Number "+i;*_
_*```*_
_*These result in compiler errors about incompatibility with GUI.Toolbar's argument type, null-reference run time errors, IndexOutOfRange exceptions, only the first entry being printed (so only a long button with "Number 0" is display), or crashing the Unity debugger. In what way is String[] different from Array(String), is the answer documented anywhere, and how may one dynamically assemble an array into String[] that GUI.Toolbar() will accept?*_
_*(On a side note, not being able to include square brackets in a Google search, or find information through Google on how to do so, is another matter.)*_

Why not use a list? Then, in your GUI.Toolbar use the ToArray() function.


import System.Collections.Generic;
var toolbarStrings : List<String> = new List.<String>();

then in your initialization

for(var i:int=0;i<=5;i++)
{
    toolbarStrings.Add("Number "+i);
}

and in your GUI:

toolbarInt = GUI.Toolbar (Rect (25, 25, 250, 30), toolbarInt, toolbarStrings.ToArray());

You could be running in to issues with the differences between javascript native array types, and Unity script’s array types.

I have successfully got the following to run:

var toolbarStrings:Array = new Array();
var toolbarInt:int = 0;

function Awake () {	
	for (var i:int = 0; i <= 5; ++i) {
		toolbarStrings.Push('# ' + i);
	}
}

function OnGUI() {
	toolbarInt = GUI.Toolbar (Rect (25, 25, 250, 30), toolbarInt, toolbarStrings.ToBuiltin(String));
}

The key part being the call to .ToBuiltin(String) to convert the Unity array to a Javascript array of strings.

Personally, I would use C# rather than Javascript, and then you would be able to use the .net List<> type to add strings dynamically, and then call .ToArray() to return you an array of strings.