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?

  • \$\begingroup\$ Do you have gameObjects in array or only numbers? \$\endgroup\$ – Hamza Hasan Dec 23 '15 at 13:54
  • \$\begingroup\$ 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. \$\endgroup\$ – Evorlor Dec 23 '15 at 13:56
  • \$\begingroup\$ But you can do it by using List and attaching a simple script containing their neighbours \$\endgroup\$ – Hamza Hasan Dec 23 '15 at 13:57
  • \$\begingroup\$ 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. \$\endgroup\$ – Evorlor Dec 23 '15 at 14:00
  • \$\begingroup\$ What exactly is the problem with using a list-like type? ie one with node members {up,down,left,right} instead of {prev,next} \$\endgroup\$ – MooseBoys Dec 23 '15 at 15:23

Break the grid into chunks of 2d map. If you have some bounds theb store these chunks in a higher level grid and read/write the chunks to disk as they come in and out of the active area. If you truly have an infinte area store the chunks in a hastable instead but remember to remove chunks that are out of the active area or else the hashtable will be too full. You could also try a two-dimensional grid that rolls the chunks overwhen new loads happen Think a 3x3 grid with the player in the middle. When the player moves too far move the chunks over and load/generate the next set of chunks.

| improve this answer | |
  • \$\begingroup\$ I miscommunicated my problem a bit, as this answer gets a bit off track. However, the idea of using a Map with the key being an x and y is exactly what I am looking for! Thanks! \$\endgroup\$ – Evorlor Dec 23 '15 at 15:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.