- Home /
passing a variable to GameObject.Find
I have 3 cubes that I want to change color. They are called Tom, Dick and Harry.
Why does this not work:
static var enemies : String[] = ["Tom", "Dick", "Harry"];
function Start () { for (var i=1; i<3; i++){ var panel = GameObject.Find(enemies[i]); panel.renderer.material.color = Color.red; }
yet this does work :
pragma strict
function Start () {
var panel1 = GameObject.Find("Tom"); panel1.renderer.material.color = Color.red;
var panel2 = GameObject.Find("Dick"); panel2.renderer.material.color = Color.red;
var panel3 = GameObject.Find("Harry"); panel3.renderer.material.color = Color.red;
}
many thanks for any help !
Regards,
Ed
Answer by Bunny83 · May 06, 2013 at 08:44 AM
Because the array index starts at 0 and not at 1. You only iterate through the numbers 1 and 2 which are "Dick" and "Harry" but you skipped "Tom"
Hi Bunny83,
thank you so much for taking the time to answer my question. I agree with you that my code omitted the first (zero index) of the array. Unfortunately that's not the only error as neither "Dick" or "Harry" responded either ! Any pointers on my syntax or type error ? gratefully received. Thank you to anyone who can help me
Regards
Ed+
Answer by Ed+ · May 06, 2013 at 07:08 PM
Thanks again to Bunny83. I started again and it now works. I have no idea what else I was doing wrong the first and second times, perhaps it was as Bunny says just the first index - I could swear that I had something else wrong though. Who knows and who cares ? I hope the little snippet of code above is of use to some other starter in the future.
Regards,
Ed