Danro/Assets/Scripts/Managers/SettingsManager.cs
Danil Iarosh 9555479967 feat(game): implement payment system and UI improvements
- Added PaymentManager integration with GameManager
- Implemented credit-based lives increment system
- Updated UI layout and anchor positions in MainMenu scene
- Added AddCredit input action bindings for keyboard and gamepad
- Refactored GameManager to use StartingLives, MaxLives properties
- Added UICreditsTextController for displaying credits and lives- Fixed prefab initialization order and component dependencies
- Updated ComWrapper serialization and prize checking logic
- Removed obsolete setLivesToDefaultAfterFirstLose setting
- Improved scene loading and player spawn management
2025-11-11 17:51:51 +03:00

166 lines
6.2 KiB
C#
Raw 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;
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;
}
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;
}
}