- Home /
How do I convert Component[] array into String[] with GetComponentsInChildren?
Hello,
I am trying to dynamically define a GUI toolbar using GetComponentsInChildren();. Basically, the number of objects that have a Waypoint script attached will appear in a gui toolbar onscreen. The idea is that you click on each of these toolbar buttons to jump to a certain area (position and rotation) in the game.
I sucessfully have my array of components listed, but how do I convert the Component[] array into a String[] variable? The attached Waypoint script defines "var objectName : String" with the game object's name.
Thanks!
Answer by duck · Mar 16, 2010 at 01:36 PM
I don't know of any simpler way than iterating through the waypoints, and populating another array - something like this:
var names = new String[waypoints.Length];
var i = 0;
for (waypoint : Component in waypoints) {
names[i++] = waypoint.name;
}
This is what I added into my script...
var Waypoints : Component[]; var WaypointsInt : int;
function Start (){
Waypoints = transform.parent.GetComponentsInChildren (Waypoint);
var WaypointsNames = String[Waypoints.Length]; var i = 0;
for (var Waypoint : Component in Waypoints) { WaypointsNames[i++] = Waypoint.name; }
}
I get the error BCE0048: Type 'System.Type' does not support slicing. Any ideas on what needs to be done differently?
Ok, that error is due to a typo in my code, it should be: new String[waypoints.Length]
. I forgot the "new" - I have updated the answer with this fix.
Awesome. Thanks for that, all works fine now. Cheers for your help.