Loop through array until certain value is found.

Hi everybody

I’ve made 2 scripts, 1 holds an array of gameobjects and I want the second script to search for the gameobject it’s attached to in the array. If this object is found I want this script to tell me in which position in the array this object can be found. How can I do this? I have been told that I must use a for loop to loop through the array, but the array also changes size. I’ve told the array to add 1 to its length if it’s completely filled.

Please help me solve this problem.

Don’t use an array, use a List.<GameObject> by importing System.Collections.Generic

List has an IndexOf function that will give you what you want. You can still write code that looks like an array - the only difference is use Count rather than length for the number or items.

The array should not change size while you’re iterating over it (if it is, stop - you need to rethink your approach to what you’re doing). You can just do a simple loop using a counter i, and access whatever element satisfies your search criteria by breaking and returning the value of i when you’re found it.

int index = -1;
for (int i = 0; i < myArray.Count; i++)
{
    if (myArray *== <whatever criteria you specify>)*

{
index = i;
break;
}
}

if (index != -1)

Alternatively, you might consider using a .Net list instead, and search for your object using List.FindIndex() using a Lambda. It returns the index of the element. For example
int index = myList.FindIndex(o => o.Name == "ObjectNameImLookingFor);
if (index != -1)