- Home /
Search for specific entity in an array?
I created an array to store a set of windows in a house, and it was populated through FindGameObjectsWithTag.
In parts of my script I need to change properties for all the windows, but how can I access a specific window (e.g, "Window01") ?
When I inspect the array, I can see they're not in any real order… Window04 Window07 Window02 etc.
…so I cannot simply do it numerically. Is there a way to perform a 'Find' within an array or is there another solution?
Answer by rutter · May 22, 2012 at 02:59 AM
The most important step here is to identify the criteria by which you'll be able to identify the particular window you're looking for. By name? By location? By some component property?
The simplest thing is to write a loop that runs through the list, looking for the item or items in question. You can write this as its own function, if you plan on performing these lookups very often.
Past that, you could use a language feature like Linq to write these lookups in shorthand. This can save time if you're a pretty experienced programmer, but is probably more trouble than its worth if you're just starting out.
Name is the only distinguisher. So something like…
for (var i = 0; i < windows.Length; i++)
{
if ( window[i].name == "Window01")
{
Window01 = window[i];
i = windows.Length;
}
}
…?
If Window01 is declared before and if you use it after then yes, this is correct.
By the way, there is a keyword to break out of a loop, it's break;. You can use it ins$$anonymous$$d of i = windows.Length;
Hmm… One last question though… Is this really the easiest way to do this if I wish to be able to manipulate almost all of the items from that array?
So if I want to get Window01, Window02 all the way to Window07, I would need to have seven 'if else' statements within my for loop, which I'm sure won't be great for performance.
Unless there's some way that I can say:
for (var i = 0; i < windows.Length; i++)
{
Declare Variable ( window[i].name ) = window[i];
}