- Home /
What's wrong with this for loop?
Hi, I'm unsure as to how I can write the following as a for loop. Basically this code works perfectly for 3 items, but I want to be able to choose how many items there are on each level which does all of this automatically instead of me having to hard code the number of items each time.
var item0 : GameObject; var item1 : GameObject; var item2 : GameObject;
var ScriptOnItem0 : DynamicListOfItemsOnItem; var ScriptOnItem1 : DynamicListOfItemsOnItem; var ScriptOnItem2 : DynamicListOfItemsOnItem;
function Start() { ScriptOnItem0 = item0.GetComponent (DynamicListOfItemsOnItem); ScriptOnItem1 = item1.GetComponent (DynamicListOfItemsOnItem); ScriptOnItem2 = item2.GetComponent (DynamicListOfItemsOnItem); }
function OnGUI() { if (listButtonPressed) { ScriptOnItem0.ShowTextures(true); ScriptOnItem1.ShowTextures(true); ScriptOnItem2.ShowTextures(true); } }
The Best I've come up with so far is;
var itemsArray : GameObject[];
var ScriptsOnItemsArray : DynamicListOfItemsOnItem[];
function Start() { for (var index : GameObject in itemsArray) { ScriptsOnItemsArray[index] = itemsArray[index].GetComponent (DynamicListOfItemsOnItem); } }
function OnGUI() { if (listButtonPressed) { for (var index : GameObject in itemsArray) { ScriptsOnItemsArray[index].ShowTextures(true); } } }
In the start function I'm trying to link the 1st array item of the script on itemsArray with the 1st variable of ScriptsOnItemsArray.
The error in Unity comes out as saying "Cannot convert 'UnityEngine.GameObject' to 'int' on the line that reads;
ScriptsOnItemsArray[index] = itemsArray[index].GetComponent (DynamicListOfItemsOnItem);
What am I doing wrong?
Thanks!
Answer by efge · Apr 09, 2011 at 08:53 AM
The index of an array is an Int so your for loop could look like this:
for (var index : int; index < itemsArray.Length; index++)
{
ScriptsOnItemsArray[index].ShowTextures(true);
}
Thanks a lot for your answer, it works! But why did my version not work? Is the way I wrote my for loop not the correct way?
You used a GameObject ins$$anonymous$$d of an Int variable to assign an element of the array.
Your answer

Follow this Question
Related Questions
Getting an error with my for/in loop! 3 Answers
Rearranging pre-existing objcets into a grid 2 Answers
using "for" in Unity Script HELP! 2 Answers
How to have a (wait) yield on a for loop? 0 Answers
How do I reset a for loop variable??? 3 Answers