Danro/Assets/Scripts/Managers/SettingsManager.cs

165 lines
6.2 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.IO;
using System.Text;
using UnityEngine;
using RR.Game2D.Core.Managers;
using RR.Common.Behaviour.ScriptableObjects;
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 static 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;
}
gameSettings.ValidateSettings();
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 GameSettings GetCurrentGameSettings() => gameSettings;
}
}