98 lines
2.8 KiB
C#
98 lines
2.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using SepCore.Definition;
|
|
using UnityEngine;
|
|
|
|
namespace SepCore.Components
|
|
{
|
|
public class StatComponent : MonoBehaviour
|
|
{
|
|
private readonly Dictionary<StatType, List<modifier>> _statModifiers = new();
|
|
private readonly Dictionary<StatType, Action<modifier, bool>> _statModifierCallbacks = new();
|
|
|
|
public void OnInit()
|
|
{
|
|
}
|
|
|
|
public void OnReset()
|
|
{
|
|
_statModifiers.Clear();
|
|
_statModifierCallbacks.Clear();
|
|
}
|
|
|
|
public void AddModifier(modifier modifier)
|
|
{
|
|
if (!_statModifiers.TryGetValue(modifier.StatType, out var modifiers))
|
|
{
|
|
modifiers = new List<modifier>();
|
|
_statModifiers.Add(modifier.StatType, modifiers);
|
|
}
|
|
modifiers.Add(modifier);
|
|
|
|
if (_statModifierCallbacks.TryGetValue(modifier.StatType, out var callbacks))
|
|
callbacks?.Invoke(modifier, true);
|
|
}
|
|
|
|
public void RemoveModifier(modifier modifier)
|
|
{
|
|
if (_statModifiers.TryGetValue(modifier.StatType, out var modifiers))
|
|
{
|
|
modifiers.Remove(modifier);
|
|
}
|
|
|
|
if (_statModifierCallbacks.TryGetValue(modifier.StatType, out var callbacks))
|
|
callbacks?.Invoke(modifier, false);
|
|
}
|
|
|
|
public void Subscribe(StatType statType, Action<modifier, bool> callback)
|
|
{
|
|
if (!_statModifierCallbacks.TryAdd(statType, callback))
|
|
{
|
|
_statModifierCallbacks[statType] += callback;
|
|
}
|
|
}
|
|
|
|
public void Unsubscribe(StatType statType, Action<modifier, bool> callback)
|
|
{
|
|
if (!_statModifierCallbacks.TryGetValue(statType, out var callbacks))
|
|
{
|
|
return;
|
|
}
|
|
|
|
callbacks -= callback;
|
|
if (callbacks == null)
|
|
{
|
|
_statModifierCallbacks.Remove(statType);
|
|
}
|
|
}
|
|
|
|
public StatProperty GetStat(StatType statType)
|
|
{
|
|
var result = new StatProperty();
|
|
|
|
if (!_statModifiers.TryGetValue(statType, out var modifiers)) return result;
|
|
|
|
foreach (var modifier in modifiers)
|
|
{
|
|
if (modifier.IsPercent) result.Percent += modifier.RealValue;
|
|
else result.Value += modifier.RealValue;
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
public void UpdateStat(StatProperty stat, modifier modifier, bool isApply)
|
|
{
|
|
float coef = isApply ? 1f : -1f;
|
|
if (modifier.IsPercent)
|
|
{
|
|
stat.Percent += modifier.RealValue * coef;
|
|
}
|
|
else
|
|
{
|
|
stat.Value += modifier.RealValue * coef;
|
|
}
|
|
}
|
|
}
|
|
}
|