Array Index

If I have an array such as:

var points : Vector3[]

and then I do something like this:

for (point in points)
{
    // do some code
}

is there some sort way I can tell where I am in the array – what element?

I know I can do it this way:

for (i = 0; i < points.length; i++)
{
   // some code
}

variable i will tell me where I am in the array, but can I do the same thing using the other for loop?

Thanks in advance for any help.

Mitch

as far as i know you would have to do it manually, i.e.

var i = 0;
for (point in points)
{
    // do some code
    i++;
}

If you use Builtin .NET arrays and each item is unique, you could also do it this way:

var vectorArray = [Vector3(0,0,1), Vector3(0,1,0), Vector3(1,0,0)];

for (item in vectorArray){
	var index = System.Array.IndexOf(vectorArray, item);
	Debug.Log(item + ", " + index);
}

EDIT: sorry tonyd, didn’t notice your disclaimer that the items have to be unique. :smiley: 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.

Thanks Tonyd - that looks like what I was searching for. When I get back home I’ll give it a go.

@FizixMan – If it doesn’t work I’ll go with the standard incremental loop.

Thanks everyone for the help. I learned a little more today.

Mitch

I seriously doubt tonyd’s solution won’t work for you as long as you know you have unique vector values and small arrays.

I do have unique vector3 values and the arrays are small. And this is only a temporary diagnostic check so even if it’s slow, it’s not an issue.

Again. many thanks!

So this works fine for an array of Vector3’s, but it does not work for an array of floats. Any thought to why that is?

It’s probably due to float imprecision.

As far as the system is concerned, there is no difference between 1.0000001 and 1.0000002.