EDIT: sorry tonyd, didn’t notice your disclaimer that the items have to be unique.
Oh well, good info all around I suppose!
tonyd’s code will only work if the items in the array are objects (and if they generate proper hash codes). If they are structs, IndexOf will return the first index of an equivalent item. The reason being that it checks equality/value of the items.
Vector3[] vectorArray = new Vector3[3] {new Vector3(1,0,0), new Vector3(0,1,0), new Vector3(0,1,0)};
foreach (Vector3 item in vectorArray)
{
int index = System.Array.IndexOf(vectorArray, item);
Debug.Log(item + ", " + index);
}
//outputs:
(1.0, 0.0, 0.0), 0
(0.0, 1.0, 0.0), 1
(0.0, 1.0, 0.0), 1
Notice the last entry points to index 1, not index 2.
Plus it’s an expensive lookup if you have a large array. But if you have a small one, and you know you have unique values, it’s fine to do it this way and save yourself the trouble of managing a counter, but I wouldn’t recommend it.
Even dbp’s method is OK for most typical cases. For arrays I think it will work fine, but for other IEnumerables, you’re not necessarily guaranteed that the foreach loop will go from start to end (for most it does though). I would suggest that unless there’s some limiting factor you’re best off using a a standard incrementing loop if you need to know the index.