Finding adjacent tiles in a grid

I have a 2D grid of tiles, and I need to build an array storing each adjacent tile of any given tile as a once-off operation. i.e. At startup, the adjacent neighbouring tiles for each tile are stored to an array.

  • The size of the tiles is known (1x1), therefore the distance between tile origins is also known.
  • Only want to find adjacent (up/down/left/right) tiles - not diagonal.

So far, there seem to be 3 obvious approaches:

  1. store all tiles to array, iterate through array to distance check with current tile position
  2. overlapsphere around position of tile, distance check (to ignore diagonals)
  3. +/- 1 to x/y of tile, small overlapsphere around the calculated position

At this stage, I'm thinking the third may be the best option, but I wanted to make sure I hadn't overlooked a better approach.

Any feedback or personal experience is welcomed and appreciated!

I assume the tiles have been created in the scene just like any other game object, which is why they're not in an array to begin with, correct? I also assume they have colliders - do they need colliders for any purpose other than finding the neighboring tiles?

As far as physics-based approaches go, I would imagine any method that would take advantage of the physics system's broad-phase culling would be fairly efficient. This would include options 2 and 3 in your list, and would also include casting a vertical ray at x/y +/- 1.

That said, the tiles' positions in the array are implicit in their xy coordinates, so another option would be to acquire references to all of the tile objects (e.g. by name, tag, or type), place them in a 2-d array based on their xy coordinates, and then compute the neighbors as you would normally. (Of course if the array would be useful for other purposes as well, you could just keep the array around and dispense with the per-tile neighbor lists entirely.)

Not sure if that's helpful at all, but maybe it'll at least provide another option to consider.

[Edit: There are other options as well, of course; one would be to create a custom editor using editor scripting, and have the editor handle the details of creating the tile array or establishing connectivity between neighboring tiles.]