/// <summary> /// Either generates or reloads chunks coming into view and unloads chunks going out of view. /// </summary> private void RegenChunks() { int posX = (int)Player.Location.X; int posY = (int)Player.Location.Y; var bottomLeft = ScreenToWorld(new Vector3(0, 0, 0)); var topRight = ScreenToWorld(new Vector3(Screen.width, Screen.height, 0)); bool hasNewChunks = false; List <Chunk> foundChunks = new List <Chunk>(); for (int y = (bottomLeft.Y - Player.ViewDis.Y).Floor(); y < (topRight.Y + Player.ViewDis.Y).Floor(); y++) { for (int x = (bottomLeft.X.Floor() - Player.ViewDis.X).Floor(); x < (topRight.X.Floor() + Player.ViewDis.X).Floor(); x++) { // If chunk is already loaded, then skip this loop if (!foundChunks.Contains(x, y)) { var loaded = Chunks.GetLoaded().GetChunkWithPosition(x, y); if (loaded != null) { foundChunks.Add(loaded); continue; } } else { continue; } // Find chunk if exists var id = new Point((int)Math.Floor(x / 16d), (int)Math.Floor(y / 16d)); //var newChunk = Chunks.GetGenerated().GetChunk(id) ?? new Chunk(id, Generator); Chunk newChunk; if (Chunks.GetGenerated().GetChunk(id) != null) { newChunk = new Chunk(id, Generator, Chunks.GetGenerated().GetChunk(id).Blocks); Debug.Log(string.Format("Found generated Chunk ID {0} with {1} blocks.", newChunk.IDStr, newChunk.Blocks.Length.ToString())); } else { newChunk = new Chunk(id, Generator); hasNewChunks = true; Chunks.Generate(newChunk); } // Chunk does not already exist, generate a new one. //if (!newChunk.IsGenerated) //{ // hasNewChunks = true; // Chunks.Generate(newChunk); //} // Load chunk Chunks.Load(newChunk, transform); } } if (hasNewChunks) { Debug.Log("Current Generated Chunks: " + Chunks.GeneratedCount()); } // Unload unneeded chunks List <Chunk> removeChunks = new List <Chunk>(); foreach (var chunk in Chunks.GetLoaded()) { if (foundChunks.GetChunk(chunk.ID) == null) { removeChunks.Add(chunk); } } Chunks.UnloadAll(removeChunks); _current = Chunks.GetLoaded().GetContains(new Point(posX, posY)); Chunks.GetLoaded().UpdateAll(); }