171 lines
6.5 KiB
C#
171 lines
6.5 KiB
C#
using System;
|
||
using System.IO;
|
||
using System.Text;
|
||
using UnityEngine;
|
||
|
||
using RR.Game2D.Core.Managers;
|
||
using RR.Common.Behaviour.ScriptableObjects;
|
||
using UnityEngine.Events;
|
||
|
||
namespace RR.Common.Managers
|
||
{
|
||
public class SettingsManager : MonoBehaviour
|
||
{
|
||
public static SettingsManager Instance { get; private set; }
|
||
|
||
[SerializeField] private GameSettings gameSettings;
|
||
|
||
private const string SETTINGS_FILE_NAME = "settings.json";
|
||
private string SettingsFilePath => Path.Combine(Application.persistentDataPath, SETTINGS_FILE_NAME);
|
||
|
||
public event Action OnSettingsLoaded;
|
||
public event Action OnSettingsSaved;
|
||
|
||
public void Initialize()
|
||
{
|
||
// ---- Singleton ----
|
||
if (Instance != null && Instance != this)
|
||
{
|
||
Destroy(gameObject);
|
||
return;
|
||
}
|
||
|
||
Instance = this;
|
||
DontDestroyOnLoad(gameObject);
|
||
// -------------------
|
||
|
||
// Loading and applying game settings
|
||
if (gameSettings == null)
|
||
{
|
||
GameManager.Logger.Log($"{name}: gameSettings is null. Устанавливаю gameSettings по умолчанию.");
|
||
gameSettings = ScriptableObject.CreateInstance<GameSettings>();
|
||
}
|
||
|
||
LoadSettings();
|
||
|
||
gameSettings.ApplySettings();
|
||
}
|
||
|
||
// Если не инициализируется в GameManager, инициализировать тут
|
||
// private void Awake()
|
||
// {
|
||
// Initialize();
|
||
// }
|
||
|
||
private void OnApplicationQuit()
|
||
{
|
||
SaveSettings();
|
||
}
|
||
|
||
public void LoadSettings()
|
||
{
|
||
if (gameSettings == null)
|
||
{
|
||
Debug.LogError($"{name}: gameSettings is null. Невозможно загрузить настройки.");
|
||
}
|
||
|
||
if (File.Exists(SettingsFilePath))
|
||
{
|
||
try
|
||
{
|
||
string json = File.ReadAllText(SettingsFilePath);
|
||
Debug.Log($"{name}: Пытаюсь загрузить настройки из: {SettingsFilePath}");
|
||
Debug.Log($"{name}: Загруженный JSON: {json}");
|
||
|
||
GameSettings tempSettings = ScriptableObject.CreateInstance<GameSettings>();
|
||
JsonUtility.FromJsonOverwrite(json, tempSettings);
|
||
|
||
tempSettings.ValidateSettings();
|
||
JsonUtility.FromJsonOverwrite(json, gameSettings);
|
||
Debug.Log($"{name}: Настройки загружены и проверены успешно.");
|
||
Destroy(tempSettings);
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
Debug.LogError($"{name}: Ошибка при загрузке настроек: {e.Message}. Применяю настройки по умолчанию.");
|
||
gameSettings.SetDefaultValues();
|
||
}
|
||
}
|
||
else
|
||
{
|
||
Debug.Log($"{name}: Настройки не найдены по пути: {SettingsFilePath}. Применяю настройки по умолчанию.");
|
||
gameSettings.SetDefaultValues();
|
||
}
|
||
|
||
gameSettings.ApplySettings();
|
||
OnSettingsLoaded?.Invoke();
|
||
}
|
||
|
||
public void SaveSettings()
|
||
{
|
||
if (gameSettings == null)
|
||
{
|
||
Debug.LogError($"{name}: gameSettings is null. Невозможно сохранить настройки.");
|
||
return;
|
||
}
|
||
|
||
try
|
||
{
|
||
string json = JsonUtility.ToJson(gameSettings, true);
|
||
File.WriteAllText(SettingsFilePath, json, Encoding.UTF8);
|
||
Debug.Log($"{name}: Настройки сохранены по пути: {SettingsFilePath}.");
|
||
Debug.Log($"{name}: Сохраненный JSON: {json}");
|
||
OnSettingsSaved?.Invoke();
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
Debug.LogError($"{name}: Ошибка при сохранении настроек: {e.Message}.");
|
||
}
|
||
}
|
||
|
||
public void SetFullscreen(bool newFullscreen)
|
||
{
|
||
gameSettings.isFullscreen = newFullscreen;
|
||
Debug.Log($"{name}: Установлен режим: {(newFullscreen ? "полноэкранный" : "оконный")}.");
|
||
}
|
||
|
||
public void SetMusicVolume(float newVolume)
|
||
{
|
||
gameSettings.musicVolume = newVolume;
|
||
Debug.Log($"{name}: Установлена громкость музыки: {newVolume}.");
|
||
}
|
||
|
||
public void SetSfxVolume(float newVolume)
|
||
{
|
||
gameSettings.sfxVolume = newVolume;
|
||
Debug.Log($"{name}: Установлена громкость звуков: {newVolume}.");
|
||
}
|
||
|
||
public void SetIsFreeGame(bool newIsFreeGame)
|
||
{
|
||
gameSettings.isFreeGame = newIsFreeGame;
|
||
Debug.Log($"{name}: Установлена флаг 'free game': {newIsFreeGame}.");
|
||
}
|
||
|
||
public void SetIsGivingPrizes(bool newIsGivingPrizes)
|
||
{
|
||
gameSettings.isGivingPrizes = newIsGivingPrizes;
|
||
Debug.Log($"{name}: Установлена флаг 'give prizes': {newIsGivingPrizes}.");
|
||
}
|
||
|
||
public void SetStartLivesCount(int newStartLivesCount)
|
||
{
|
||
gameSettings.startLivesCount = newStartLivesCount;
|
||
Debug.Log($"{name}: Установлен количество жизней: {newStartLivesCount}.");
|
||
}
|
||
|
||
public void SetLivesIncreasedByCredits(int newLivesIncreasedByCredits)
|
||
{
|
||
gameSettings.livesIncreasedByCredits = newLivesIncreasedByCredits;
|
||
Debug.Log($"{name}: Установлены жизни при пополнении баланса: {newLivesIncreasedByCredits}.");
|
||
}
|
||
|
||
public void SetSetLivesToDefaultAfterFirstLose(bool newSetLivesToDefaultAfterFirstLose)
|
||
{
|
||
gameSettings.setLivesToDefaultAfterFirstLose = newSetLivesToDefaultAfterFirstLose;
|
||
Debug.Log($"{name}: Установлен флаг 'set lives to default after first lose': {newSetLivesToDefaultAfterFirstLose}.");
|
||
}
|
||
|
||
public GameSettings GetCurrentGameSettings() => gameSettings;
|
||
}
|
||
} |