[ArrayUtility][1] is a Editor class, which means it can not be used to make scripts for the game.
Fortunately, you can use [System.Array.FindIndex()][2]. This function is a [static function][3], as well as a [C# generic][4]. If you aren’t familiar with either concepts, I suggest you read both articles I’ve linked for a more details.
Generics let programmers write code where certain types can be defined later, like a fill-in-the-blank.
Example:
T GetAtIndex<T>(T[] pArray, int i)
{
return pArray*;*
}
Since it is a generic function, when it is used, you have to specify what kind of type T
will be:
int[] myArray1 = {1, 2, 4, 0, 23};
int[] myArray2 = {false, false, false, true};
int element1 = GetIndex(myArray1, 2); // 4
bool element2 GetIndex(myArray2, 3); // true
For the first one, all T
’s are replaced with int
, and for the second, all T
’s are replaced with bool
. Whatever replaces the T
must be a type, such as GameObject
, Component
, int
, bool[]
, etc. In some cases, you don’t even have to specify what T is - the compiler will figure that out for you:
// decides that T is an int because of myArray1’s type
int element1 = GetIndex(myArray1, 2);
// decides that T is a bool, same reason
bool element2 GetIndex(myArray2, 3); // true
Now, back to System.Array.FindIndex()
. According to the [MSDN documentation of it][2], you give it a T[]
for the array and a System.Predicate
for the match function. Predicate
is a delegate, which is a variable that can store a reference any function that follows a pattern. The pattern for Predicate
is:
bool functionName(T pValue);
When FindIndex()
goes through each element in the array, it calls the predicate function and passes the element in. If predicate then returns true, FindIndex will return the index for that element. If the predicate returns false for all the elements, FindIndex()
returns -1 instead. So, the predicate is the most important part of how FindIndex()
works, because whichever function you pass in as the predicate decides what index gets returned.
Here’s an example of how it all works:
// the location of FindIndex and Predicate
using System;
// …
bool MatchFunction1(string arrayElement)
{
// returns true if the element matches “GHI”
return arrayElement == “GHI”;
}
bool MatchFunction2(string arrayElement)
{
// returns true if the element matches “MNO”
return arrayElement == “MNO”;
}
// …
string[] myArray = { “ABC”, “DEF”, “GHI”, “JKL” };
// index will be 2
int index = Array.FindIndex(myArray, MatchFunction1);
// no match found, index will be -1
int index = Array.FindIndex(myArray, MatchFunction2);
[1]: Unity - Scripting API: ArrayUtility.FindIndex
[2]: Array.FindIndex Method (System) | Microsoft Learn
[3]: http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx
[4]: An Introduction to C# Generics | Microsoft Learn