using System; using System.Collections.Generic; using System.Linq; using UnityEngine; internal class ChildInventotyWithCallback { public readonly IInventory inventory; public readonly Action callback; public ChildInventotyWithCallback(IInventory inventory, Action callback) { this.inventory = inventory; this.callback = callback; } } [Serializable] public class VirtualInventory : IInventory { private readonly List _children = new List(); public override IReadOnlyDictionary Items { get { var items = new Dictionary(); foreach (var child in _children) { foreach (var childItem in child.inventory.Items) { if (!items.ContainsKey(childItem.Key)) items.Add(childItem.Key, childItem.Value); else items[childItem.Key] += childItem.Value; } } return items; } } public override float Capacity { get => _children.Sum(c => c.inventory.Capacity); set { throw new NotSupportedException(); } } public void RegisterChild(IInventory child) { Debug.Log($"Registered child {child}"); var reg = new ChildInventotyWithCallback(child, () => OnChildChange(child)); _children.Add(reg); child.RegisterOnChangeCallback(reg.callback); } public void UnregisterChild(IInventory child) { int index = _children.FindIndex(c => c.inventory == child); if (index < 0) return; child.UnregisterOnChangeCallback(_children[index].callback); _children.RemoveAt(index); } private void OnChildChange(IInventory child) { Debug.Log($"child has changed {child}"); base.InvokeOnChange(); } public override float GetAmount(string item) { float amount = 0; Items.TryGetValue(item, out amount); return amount; } protected override float DoAdd(string item, float amount, bool allowPartialAdd = false) { throw new NotSupportedException(); } protected override int DoClear() { throw new NotSupportedException(); } protected override float DoRemove(string item, float amount, bool allowPartialRemoval = false) { throw new NotSupportedException(); } }