unity-roject-test/Assets/Scripts/Rokojori/GameState/GameStateManager.cs

124 lines
3.0 KiB
C#
Raw Normal View History

2026-09-25 20:32:02 +00:00
using System.Collections.Generic;
using UnityEngine;
namespace Rokojori
{
public class GameStateManager : MonoBehaviour
{
public static GameStateManager instance => Unique<GameStateManager>.Get();
public List<GameStateVariable> variables = new List<GameStateVariable>();
[System.NonSerialized]
public Dictionary<GameStateNumberVariable, double> _numberValues = new Dictionary<GameStateNumberVariable, double>();
[System.NonSerialized]
public Dictionary<GameStateBoolVariable, bool> _boolValues = new Dictionary<GameStateBoolVariable, bool>();
public void Awake()
{
_numberValues.Clear();
_boolValues.Clear();
variables.ForEach( v =>
{
if ( v is GameStateNumberVariable numberVariable )
{
_numberValues[ numberVariable ] = numberVariable.initialValue;
}
else if ( v is GameStateBoolVariable boolVariable )
{
_boolValues[ boolVariable ] = boolVariable.initialValue;
}
} );
}
public double GetValue( GameStateNumberVariable variable )
{
return _numberValues.TryGetValue( variable, out var value ) ? value : variable.initialValue;
}
public bool GetValue( GameStateBoolVariable variable )
{
return _boolValues.TryGetValue( variable, out var value ) ? value : variable.initialValue;
}
public void SetValue( GameStateNumberVariable variable, double value )
{
_numberValues[ variable ] = value;
variable.onChanged.DispatchEvent( value );
}
public void SetValue( GameStateBoolVariable variable, bool value )
{
_boolValues[ variable ] = value;
variable.onChanged.DispatchEvent( value );
}
[System.Serializable]
public class NumberEntry
{
public string key = "";
public double value = 0;
}
[System.Serializable]
public class BoolEntry
{
public string key = "";
public bool value = false;
}
[System.Serializable]
public class SaveData
{
public List<NumberEntry> numbers = new List<NumberEntry>();
public List<BoolEntry> bools = new List<BoolEntry>();
}
public string ToJson()
{
var data = new SaveData();
foreach ( var pair in _numberValues )
{
data.numbers.Add( new NumberEntry{ key = pair.Key.key, value = pair.Value } );
}
foreach ( var pair in _boolValues )
{
data.bools.Add( new BoolEntry{ key = pair.Key.key, value = pair.Value } );
}
return JsonUtility.ToJson( data );
}
public void FromJson( string json )
{
var data = JsonUtility.FromJson<SaveData>( json );
data.numbers.ForEach( entry =>
{
var variable = variables.Find( v => v is GameStateNumberVariable n && n.key == entry.key ) as GameStateNumberVariable;
if ( variable != null )
{
SetValue( variable, entry.value );
}
} );
data.bools.ForEach( entry =>
{
var variable = variables.Find( v => v is GameStateBoolVariable b && b.key == entry.key ) as GameStateBoolVariable;
if ( variable != null )
{
SetValue( variable, entry.value );
}
} );
}
}
}