Files
2026-07-21 08:56:10 +03:00

123 lines
3.4 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using NaughtyAttributes;
using UnityEngine;
public class EnvironmentObserver : MonoBehaviour
{
private Environment environment;
private CommandSaveHandler commandSaveHandler;
[SerializeField] private bool autoSaving = true;
private bool canSave = true;
private bool isLoading = false;
private Coroutine loadCoroutine;
private void Start()
{
environment = Environment.getInstance();
commandSaveHandler = CommandSaveHandler.getInstance();
environment.onChangeEvent.AddListener(onChange);
}
private void onChange()
{
if (autoSaving && canSave && !isLoading)
save();
}
public void save()
{
if (isLoading)
{
Debug.LogWarning("Cannot save while a load operation is in progress.");
return;
}
commandSaveHandler.clearCommandList();
addAllCommands();
commandSaveHandler.saveCommands();
}
public void saveToPath(string path)
{
if (isLoading)
{
Debug.LogWarning("Cannot save while a load operation is in progress.");
return;
}
commandSaveHandler.clearCommandList();
addAllCommands();
commandSaveHandler.saveCommandsToPath(path);
}
[Button("load")]
public void load()
{
if (loadCoroutine != null)
{
StopCoroutine(loadCoroutine);
loadCoroutine = null;
}
isLoading = true;
canSave = false;
environment.clearEnvironment();
commandSaveHandler.clearCommandList();
commandSaveHandler.loadCommands();
loadCoroutine = StartCoroutine(commandSaveHandler.excuteAllCommands(() => {
loadCoroutine = null;
StartCoroutine(reloadSave());
}));
}
public void loadFromPath(string path)
{
if (loadCoroutine != null)
{
StopCoroutine(loadCoroutine);
loadCoroutine = null;
}
isLoading = true;
canSave = false;
environment.clearEnvironment();
commandSaveHandler.clearCommandList();
commandSaveHandler.loadCommandsFromPath(path);
loadCoroutine = StartCoroutine(commandSaveHandler.excuteAllCommands(() => {
loadCoroutine = null;
StartCoroutine(reloadSave());
}));
}
private IEnumerator reloadSave()
{
// Wait for 1 full second to ensure all physics collisions and delayed events have fully settled
yield return new WaitForSeconds(1f);
isLoading = false;
canSave = true;
Debug.Log("Loading complete. Auto-save is now re-enabled.");
}
private void addAllCommands()
{
Dictionary<string, Block> blockRegistry = environment.getBlockRegistry();
foreach (var blockEntry in blockRegistry)
{
if (blockEntry.Value != null)
{
string prefabId = blockEntry.Value.getBlockData()?.blockName;
Vector3 position = blockEntry.Value.transform.position;
Quaternion rotation = blockEntry.Value.transform.rotation;
ICommand createCommand = new CreateBlockCommand(prefabId, position, rotation);
commandSaveHandler.addLastCommand(createCommand.toDTO());
}
}
}
}