Darstellung68 Zeilen
WorldHost.cs
Hält die Welt, verteilt sie auf Chunks und baut beim Setzen oder Abbauen die betroffenen Chunks neu — inklusive Ausrichtung, die Treppen beim Platzieren mitbekommen.
Assets/Scripts/WorldHost.cs
using System.Collections.Generic;
using UnityEngine;
namespace Blockwerk
{
/// <summary>Die laufende Welt: Blockzugriff und Chunk-Neuaufbau an einer Stelle.</summary>
public class WorldHost : MonoBehaviour
{
public static WorldHost Instance { get; private set; }
public VoxelWorld World { get; private set; }
private readonly Dictionary<Vector2Int, WorldChunk> _chunks =
new Dictionary<Vector2Int, WorldChunk>();
public void Build(VoxelWorld world)
{
Instance = this;
World = world;
int size = ChunkMesher.ChunkSize;
for (int x = 0; x < VoxelWorld.SizeX; x += size)
{
for (int z = 0; z < VoxelWorld.SizeZ; z += size)
{
var chunkObject = new GameObject("Chunk " + x + "/" + z);
chunkObject.transform.SetParent(transform, false);
var chunk = chunkObject.AddComponent<WorldChunk>();
chunk.Build(world, x, z);
_chunks[new Vector2Int(x, z)] = chunk;
}
}
}
public BlockType GetBlock(int x, int y, int z)
{
return World.Get(x, y, z);
}
/// <summary>Setzt einen Block und baut die Chunks neu, die ihn zeigen.</summary>
public void SetBlock(int x, int y, int z, BlockType type, int facing = 0)
{
if (!World.Set(x, y, z, type, facing)) return;
RebuildAround(x, z);
}
private void RebuildAround(int x, int z)
{
int size = ChunkMesher.ChunkSize;
foreach (KeyValuePair<Vector2Int, WorldChunk> entry in _chunks)
{
Vector2Int origin = entry.Key;
bool nearby =
x >= origin.x - 1 && x <= origin.x + size &&
z >= origin.y - 1 && z <= origin.y + size;
if (nearby) entry.Value.Build(World, origin.x, origin.y);
}
}
private void OnDestroy()
{
if (Instance == this) Instance = null;
}
}
}