- Home /

# Iterate through an array

How can I iterate through a Vector3 array, and for every Vector3, check to see whether there is a neighbouring one?

So for example if my array is (0,0,0), how can I check if (1,0,0) is there?

By neighbouring, I mean if they were 1,1,1 blocks, they would be touching. So an increase in 1 co-ordinate, but not the others.

Edit: Here is my new technique, using a 3D array. However, I get an error - 'not a widening conversion.' Could anyone shed any light on this?

```
var cubeSide : float;
var cubePrefab : GameObject;
var cube : int[,,];
function Start()
{
cube = new int[cubeSide,cubeSide,cubeSide];
Generate();
}
function Generate()
{
for(var x = 0; x < cubeSide - 1; x++)
for(var y = 0; y < cubeSide - 1; y++)
for(var z = 0; z < cubeSide - 1; z++)
{
var t = Random.value;
t = Mathf.Round(t);
cube[x,y,z] = t;
}
Build();
Check();
}
function Check()
{
for(var x = 0; x < cubeSide - 1; x++)
for(var y = 0; y < cubeSide - 1; y++)
for(var z = 0; z < cubeSide - 1; z++)
{
if(z != cube.Length - 1) if(cube[x,y,z + 1] == 1) print(""); //there is something at the front
if(z != 0) if(cube[x,y,z - 1] == 1) print(""); //there is something at the back
if(x != 0) if(cube[x - 1,y,z] == 1) print(""); //there is something at the left
if(x != cube.Length - 1) if(cube[x + 1,y,z] == 1) print(""); //there is something at the right
if(y != cube.Length - 1) if(cube[x,y + 1,z] == 1) print(""); //there is something above
if(y != 0) if(cube[x,y - 1,z] == 1) print(""); //there is something underneath
}
Build();
}
```

You might want to spellcheck the title of your question in order to get more answers.

42 minutes later, it's already off the front page. I think UA needs a way of informing posters of what's going on. Remember the new posts envelope with the last version?

I think they said that, that could not be done. Or that it was a furture feature. I am not sure.

I really want that envelope as well.

In your approach, you never reset the values of nx, px, ny, etc., so once one of them gets set to "true", it stays "true" for the rest of the loop. You can both compress your code and solve that problem if, instead of the if(j.x...)nx=... you just put the statement nx=(j.x-i.x == -1); , and similary for the other 5 cases.

**Answer** by Wolfram
·
Nov 22, 2011 at 09:01 PM

(Responding to the current code example, which no longer has a lot to do with the bulk of the question)

When using this:

```
t = Mathf.Round(t);
```

, "t" is still a float. Assigning that to an int cube element will give the error you posted.

Instead, do this:

```
var t = Random.value;
cube[x,y,z] = Mathf.RoundToInt(t);
```

I'll accept this, and call it a day on this question. Interesting discussion. BTW, does your name come from the German word for 'Tungsten'?

Well, it is the German word for Tungsten, but the name's origin is nordic, I think, from "wolf" and "raven", or something.

Note you probably want to get rid of the "-1" in all of your for loop declarations: if cubeSide is, say, 4, your current loop runs from 0 to i<3, which is only 0,1, and 2, so the outer shell at three sides of your cube will always be empty. Further down, I'm not sure you can use "z != cube.Length - 1", but I don't know jagged arrays very well. Instead, you could simply use "z != cubeSide - 1", assuming you also remove the -1's mentioned above.

**Answer** by CHPedersen
·
Nov 16, 2011 at 10:54 AM

Vector coordinates are floating point quantities, so "neighbouring" doesn't make a whole lot of sense, but if (0,0,0) and (1,0,0) are "neighbouring", perhaps you can use the distance between them to determine this relationship?

I.e., for every vector in your array, check if there exists another vector in your array, the distance to which is 1. Something like this:

```
public void VectorTest()
{
Vector3[] vectors = new Vector3[100];
```

```
```

```
foreach (Vector3 targetVec in vectors)
{
foreach (Vector3 testedAgainst in vectors)
{
if(Vector3.Distance(targetVec, testedAgainst) == 1.0f)
// targetVec and testedAgainst are "neighbours"
}
}
```

}

Please beware that this is grossly inefficient - it runs in N^2-time, because it traverses the full array in a nested manner. So it's liable to get slow if the amount of vectors is high. Also note that the distance between two vectors is the euclidian distance, i.e. what Vector3.Distance actually calculates is Sqrt((x2-x1)^2 + (y2-y1)^2 + (z2-z1)^2). But since you're testing to see if the distance is 1, it means that the squared distance is also 1. So you don't have to take the squareroot of that to determine the result. You could write your own distance formula for the purpose of skipping that particular calculation. It would speed the calculation up.

elegant solution, my solution below just offers a slightly simplistic approach only check a single Vector. <3 Math

Note with this approach you cannot distinguish between truly neighboring vectors (or vectors that have the same value), and identical vectors, since you iterate over the same array. Instead, a for-loop might be better: for(int i=0;i

Ah, I see you compare to Distance==1, in which case my comment is not relevant. But I assume the Distance==1 condition was just an example, usually you would compare Distance

This entire discussion depends on what the OP defines to be "neighbour". My solution is based on "neighbour" meaning distance == 1, because that is a characteristic trait with the example he gave. If two vectors are "neighbours" if their distance is merely less than some threshold, then you can simply skip matches found in my solution if the hashcodes are the same (Vector3.GetHashCode()) because this means identical vectors, or, as you say, you can use two regular for-loops and skip where the inner iterator matches the outer.

Agreed. Nice idea to use GetHashCode(), didn't think of that.

**Answer** by Wolfram
·
Nov 16, 2011 at 12:55 PM

Starting from Christian's approach, here is a more general and slightly optimized version of finding neighbouring vectors (C#):

```
public void VectorTest()
{
Vector3[] vectors = new Vector3[100];
for(int i=0;i<vectors.Length-1;i++)
{
// no need to compare twice agains smaller indices, so start at i+1
for(int j=i+1;j<vectors.Length;j++)
{
if(Vector3.Distance(vectors[i], vectors[j]) <= 1.0f)
// vectors[i] and vectors[j] are "neighbours"
}
}
}
```

Again, as Christian mentions, this assumes "neighbouring" is defined by the 3D distance of two vectors. If you mean something else by "neighbouring", please elaborate.

**Answer** by Caiuse
·
Nov 16, 2011 at 11:02 AM

The best way would be to use a for loop and compare each next element's x value against the current elements x + 1.

```
function compareEachElement() : boolean {
var trueCount : int;
for(var i = 0; i < myArray.length; i++){
//check the that next elements x value is equal to the current elements x + 1
var currentElement = myArray[i];
var nextElement = myArray[i + 1];
if( nextElement .x == currentElement.x + 1)
trueCount ++;
}
if(trueCount == myArray.length) return true;
}
```

if you wanted to compare a specific element in the array, then pass in an index to compare like so:

```
function compareSpecificElement( index : int ) : boolean {
var specificElement = myArray[ index ];
var nextElement = myArray[index + 1];
if( nextElement .x == specificElement.x + 1)
return true;
}
```

Note that this approach would only work for the very explicit case that "neighbouring" means the elements differ in x by exactly 1, ignoring y and z differences, and ignoring differences smaller than 1, or even -1. Also, this approach relies upon the array being sorted. For example, cases like this will not be catched: myArray[0]=(3,0,0) myArray[4]=(4,0,0). In addition, you will get an out-of-bounds error, since you are accessing myArray[myArray.Length] at the end of your loop.

I agree, although the out-of-bounds error could be solved with an IF, if(i + 1 < myArray.length)

### Your answer

### Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.