A game about forced loneliness, made by TACStudios
1using System; 2using System.Collections.ObjectModel; 3 4namespace Unity.VisualScripting 5{ 6 public sealed class UnitPortCollection<TPort> : KeyedCollection<string, TPort>, IUnitPortCollection<TPort> 7 where TPort : IUnitPort 8 { 9 public IUnit unit { get; } 10 11 public UnitPortCollection(IUnit unit) 12 { 13 this.unit = unit; 14 } 15 16 private void BeforeAdd(TPort port) 17 { 18 if (port.unit != null) 19 { 20 if (port.unit == unit) 21 { 22 throw new InvalidOperationException("Node ports cannot be added multiple time to the same unit."); 23 } 24 else 25 { 26 throw new InvalidOperationException("Node ports cannot be shared across nodes."); 27 } 28 } 29 30 port.unit = unit; 31 } 32 33 private void AfterAdd(TPort port) 34 { 35 unit.PortsChanged(); 36 } 37 38 private void BeforeRemove(TPort port) 39 { 40 } 41 42 private void AfterRemove(TPort port) 43 { 44 port.unit = null; 45 unit.PortsChanged(); 46 } 47 48 public TPort Single() 49 { 50 if (Count != 0) 51 { 52 throw new InvalidOperationException("Port collection does not have a single port."); 53 } 54 55 return this[0]; 56 } 57 58 protected override string GetKeyForItem(TPort item) 59 { 60 return item.key; 61 } 62 63 public new bool TryGetValue(string key, out TPort value) 64 { 65 if (Dictionary == null) 66 { 67 value = default(TPort); 68 return false; 69 } 70 71 return Dictionary.TryGetValue(key, out value); 72 } 73 74 protected override void InsertItem(int index, TPort item) 75 { 76 BeforeAdd(item); 77 base.InsertItem(index, item); 78 AfterAdd(item); 79 } 80 81 protected override void RemoveItem(int index) 82 { 83 var item = this[index]; 84 BeforeRemove(item); 85 base.RemoveItem(index); 86 AfterRemove(item); 87 } 88 89 protected override void SetItem(int index, TPort item) 90 { 91 throw new NotSupportedException(); 92 } 93 94 protected override void ClearItems() 95 { 96 while (Count > 0) 97 { 98 RemoveItem(0); 99 } 100 } 101 } 102}