- Home /
Smooth chunk saving and loading
I'm creating a minecraft-style game which is chunk based. Here is the repo: https://github.com/JoshPJackson/BlockGame.
I am having some performance issues with the saving and loading of chunks. Each update of the game checks which chunks are within a certain range. If the chunk is within a certain range, and isn't already loaded, then it will be loaded from a file. If a chunk is loaded but is not out of the range of the player then it is saved to a file and then deleted.
// Update is called once per frame
void Update()
{
Render();
}
void Render()
{
currentPosition = Camera.main.transform.position;
for (int x = 0; x < world.Size.x; x++)
{
chunkPosition.x = x;
for (int y = 0; y < world.Size.y; y++)
{
chunkPosition.z = y;
for (int i = 0; i < ChunkColumn.chunksPerColumn; i++)
{
chunkPosition.y = i;
if (
Math.Abs(currentPosition.x / Chunk.size - chunkPosition.x) < radius.x &&
Math.Abs(currentPosition.z / Chunk.size - chunkPosition.z) < radius.z &&
Math.Abs(currentPosition.y / Chunk.size - i) < radius.y
)
{
if (world.chunkColumns[x, y].chunks[i] == null)
{
Chunk chunk = Chunk.Load(new Vector2(x, y), i);
world.loaded++;
world.chunkColumns[x, y].chunks[i] = chunk;
chunk.Render();
chunk.Optimize();
return;
}
}
else
{
if (world.chunkColumns[x, y].chunks[i] != null)
{
world.chunkColumns[x, y].chunks[i].Save();
world.chunkColumns[x, y].chunks[i].Destroy();
world.chunkColumns[x, y].chunks[i] = null;
world.loaded--;
return;
}
}
}
}
}
}
The saving process simply goes through all the blocks in the chunk and writes their type to a new line in the chunk text file. Loading a chunk basically does the opposite.
My game is constantly stuttering when the player is moving because of this (I think).
I would like some advice for how to handle this. I was wondering if it was better to deactivate chunks and then have a separate task to remove them, but I'm not sure how to acheive this.
Your answer
Follow this Question
Related Questions
Big problem on chunk generation (Unity Tilemaps) 1 Answer
Need help fixing procedural generation bug 1 Answer
Multiple GUI Cameras peformance consideration 0 Answers
Faces vs. Materials 0 Answers
Does having a gameobject at the origin affect performance if the player is far from the origin? 0 Answers