# How should I store a procedurally generated grid level of an infinite size?

I have a 2d grid level. It infinitely grows. If it was not of infinite size, a 2D array would be perfect, as I need to constantly have each grid talk to its neighbors.

For example, with a 2D array, I can talk to its top neighbor by saying var topNeighbor = myGrid[x,y+1];

But if I were to use a List, the indices would be changing.

If I just store a list of all grid separately and then iterate through them for each grid, thats an n^2 algorithm running each frame. Each room would have to iterate through every other room just to ask if they were neighbors.

What is the best way to store a 2D grid of an unknown size, assuming each grid needs to talk to its 4 neighboring grids every frame?

• Do you have gameObjects in array or only numbers? – Hamza Hasan Dec 23 '15 at 13:54
• I have an infinite number of GameObjects which are aligned in a perfect grid. Side note: They do not have colliders, nor do I want them. – Evorlor Dec 23 '15 at 13:56
• But you can do it by using List and attaching a simple script containing their neighbours – Hamza Hasan Dec 23 '15 at 13:57
• I have considered that. But each GameObject occupies an unknown number of grids, and there are an unknown number of neighbors. This means I would need to iterate through every other GameObject when one is created to make a list of its neighbors. Then iterate through each neighbor to find the one I am looking for every frame. It is definitely better than what I have been doing, so thanks! But I am hoping to find some elegant solution if one exists. – Evorlor Dec 23 '15 at 14:00
• What exactly is the problem with using a list-like type? ie one with node members {up,down,left,right} instead of {prev,next} – MooseBoys Dec 23 '15 at 15:23