How do you use IndexOf() or FindIndex()

I am trying to get the variable from the array as displayed below, I am not able to get the index as it always throws an error.

var array : Array = [0,3,5,6,1000,2,3,5];
var findIndex : int = 1000;
var index = array.FindIndex(findIndex); //Doesn't work
var index2 = array.IndexOf(findIndex);  //Also doesn't work but gives different error

I have looked at the scripting reference but I still cant get it to work. Some help would be appreciated thanks :slight_smile:

2 Answers

2

Don’t use the Array class, use a built-in array or generic List. For built-in arrays, use System.Array.IndexOf (array, item). For a List, use list.IndexOf (item). See the MSDN docs for all .NET functions. These are not covered in the Unity scripting reference, because they’re already covered on MSDN. (Technically the Mono documentation would be more appropriate, but it’s incomplete and of limited use compared to MSDN.)

It should be:

var firstOddNumberIndex = Array.FindIndex( array, IsOdd );

function IsOdd( val : int ) : boolean {
   return ( val % 2 ) != 0;
}

The first parameter is your array, the second parameter is a function to check the element in the array. FindIndex() will return the index of the first element that matches the condition of the function, or else it will return 0 if nothing is found.

var index = Array.IndexOf( array, 100 );

IndexOf will return the index of the first occurrence of 100 in the array. For example, { 0, 100, 100, 10 } will return 1.