using System; using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityEngine.Events; public class Environment : MonoBehaviour { private static Environment instance; private Dictionary blockRegistry = new Dictionary(); public UnityEvent onBlockAddedEvent; public UnityEvent onBlockMovedEvt; public UnityEvent onBlockRemovedEvent; public UnityEvent onChangeEvent; public static Environment getInstance() { if (instance == null) { instance = FindObjectOfType(); if (instance == null) { GameObject environmentObject = new GameObject("Environment"); instance = environmentObject.AddComponent(); } } return instance; } public Dictionary getBlockRegistry() { return blockRegistry; } private void Awake() { if (instance == null) { instance = this; } else { Destroy(gameObject); } } public void addBlock(Block block, string existingUUID = null) { // 1. Assign ID: Use existing (Undo/Redo) or generate a new one (Fresh placement) string uuid = string.IsNullOrEmpty(existingUUID) ? Guid.NewGuid().ToString() : existingUUID; block.setBlockId(uuid); // 2. Register in the dictionary if (!blockRegistry.ContainsKey(uuid)) { blockRegistry.Add(uuid, block); } else { blockRegistry[uuid] = block; // Update reference if already exists } applyChanges(); onBlockAddedEvent.Invoke(block); } public void moveBlock(Block block, Vector3 oldPos, Quaternion oldRot, Vector3 newPos, Quaternion newRot) { block.transform.SetPositionAndRotation(newPos, newRot); onBlockMovedEvt.Invoke(block, oldPos, oldRot); applyChanges(); } public void removeBlock(string uuid) { if (blockRegistry.TryGetValue(uuid, out Block block)) { onBlockRemovedEvent.Invoke(block); blockRegistry.Remove(uuid); applyChanges(); } } public void applyChanges() { onChangeEvent.Invoke(); } public void completeDestroyBlock(Block block) { if (block != null) Destroy(block.gameObject); } public Block getBlock(string uuid) { if (blockRegistry.TryGetValue(uuid, out Block block)) { return block; } return null; } public void clearEnvironment() { foreach (var blockEntry in blockRegistry) { if (blockEntry.Value != null) { Destroy(blockEntry.Value.gameObject); } } blockRegistry.Clear(); } }