# Information/context

I'm writing a 2D sandbox game - similar to Terraria. The world is made up of many chunks, in a variable like this:

vector<Chunk> chunks;


There's no need to go too in depth about the Chunk class, but each chunk has these members:

int x, y;
Block blocks[256];


When a chunk is initialized, the blocks are all set (with a Perlin noise based algorithm.) There are 256 blocks per every chunk because a chunk is a 16x16 area filled with blocks. To the loading of the chunks, the members of the Block class are irrelevant.

# Question

As the player walks around the world, I obviously need new chunks to load for them to explore. I don't think it needs saying but I shouldn't load every chunk in the world at once because:

• It would be incredibly inefficient to render (even with my current system of block culling,) and
• I don't know how many chunks will be in the world - there can be a huge amount, basically as many as the player wants to load.

I've tried a few different (but similar) ways to load and unload the chunks, but none of them worked very well. The main problem with both was that they sometimes gave segmentation faults.

What's the best way to dynamically load and unload chunks in a world?

By "best", I mean the most performance-efficient method.

Keep in mind I can easily load a chunk at any position - this isn't the problem. I just want a way of deciding which chunks to load.