From 70e80f76cbe1bc33ffffe56d69269d4959fbf4e3 Mon Sep 17 00:00:00 2001 From: Konstantin Dyachenko Date: Sun, 29 Mar 2026 03:11:19 +0700 Subject: [PATCH] [Add] Chunk Limit --- .../WorldGen/InfiniteWorldGenerator.cs | 49 ++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/Assets/Scripts/WorldGen/InfiniteWorldGenerator.cs b/Assets/Scripts/WorldGen/InfiniteWorldGenerator.cs index a9fea258..d927c7ac 100644 --- a/Assets/Scripts/WorldGen/InfiniteWorldGenerator.cs +++ b/Assets/Scripts/WorldGen/InfiniteWorldGenerator.cs @@ -60,7 +60,7 @@ namespace InfiniteWorld } lastGeneratedCenter = playerChunk; - GenerateAround(playerChunk); + UpdateActiveChunks(playerChunk); } private void EnsureSceneInfrastructure() @@ -111,6 +111,12 @@ namespace InfiniteWorld return true; } + private void UpdateActiveChunks(Vector2Int centerChunk) + { + GenerateAround(centerChunk); + UnloadDistantChunks(centerChunk); + } + private void GenerateAround(Vector2Int centerChunk) { for (int y = -generationRadius; y <= generationRadius; y++) @@ -132,6 +138,47 @@ namespace InfiniteWorld } } + private void UnloadDistantChunks(Vector2Int centerChunk) + { + List coordsToRemove = new List(); + foreach (KeyValuePair pair in chunks) + { + if (IsWithinActiveRadius(pair.Key, centerChunk)) + { + continue; + } + + coordsToRemove.Add(pair.Key); + } + + for (int i = 0; i < coordsToRemove.Count; i++) + { + Vector2Int coord = coordsToRemove[i]; + if (!chunks.TryGetValue(coord, out GeneratedChunk chunk)) + { + continue; + } + + chunks.Remove(coord); + if (chunk.Root != null) + { + Destroy(chunk.Root.gameObject); + } + + RefreshNeighborBorders(coord + Vector2Int.up); + RefreshNeighborBorders(coord + Vector2Int.right); + RefreshNeighborBorders(coord + Vector2Int.down); + RefreshNeighborBorders(coord + Vector2Int.left); + } + } + + private bool IsWithinActiveRadius(Vector2Int coord, Vector2Int centerChunk) + { + int dx = Mathf.Abs(coord.x - centerChunk.x); + int dy = Mathf.Abs(coord.y - centerChunk.y); + return dx <= generationRadius && dy <= generationRadius; + } + private GeneratedChunk CreateChunk(Vector2Int coord) { GameObject chunkObject = new GameObject($"Chunk_{coord.x}_{coord.y}");