A game about forced loneliness, made by TACStudios
1using System.Collections.Generic; 2 3namespace Unity.VisualScripting 4{ 5 [TypeIcon(typeof(ISelectUnit))] 6 public abstract class SelectUnit<T> : Unit, ISelectUnit 7 { 8 // Using L<KVP> instead of Dictionary to allow null key 9 [DoNotSerialize] 10 public List<KeyValuePair<T, ValueInput>> branches { get; private set; } 11 12 [Inspectable, Serialize] 13 public List<T> options { get; set; } = new List<T>(); 14 15 /// <summary> 16 /// The value on which to select. 17 /// </summary> 18 [DoNotSerialize] 19 [PortLabelHidden] 20 public ValueInput selector { get; private set; } 21 22 /// <summary> 23 /// The output value to return if the selector doesn't match any other option. 24 /// </summary> 25 [DoNotSerialize] 26 public ValueInput @default { get; private set; } 27 28 /// <summary> 29 /// The selected value. 30 /// </summary> 31 [DoNotSerialize] 32 [PortLabelHidden] 33 public ValueOutput selection { get; private set; } 34 35 public override bool canDefine => options != null; 36 37 protected override void Definition() 38 { 39 selection = ValueOutput(nameof(selection), Result).Predictable(); 40 41 selector = ValueInput<T>(nameof(selector)); 42 43 Requirement(selector, selection); 44 45 branches = new List<KeyValuePair<T, ValueInput>>(); 46 47 foreach (var option in options) 48 { 49 var key = "%" + option; 50 51 if (!valueInputs.Contains(key)) 52 { 53 var branch = ValueInput<object>(key).AllowsNull(); 54 branches.Add(new KeyValuePair<T, ValueInput>(option, branch)); 55 Requirement(branch, selection); 56 } 57 } 58 59 @default = ValueInput<object>(nameof(@default)); 60 61 Requirement(@default, selection); 62 } 63 64 protected virtual bool Matches(T a, T b) 65 { 66 return Equals(a, b); 67 } 68 69 public object Result(Flow flow) 70 { 71 var selector = flow.GetValue<T>(this.selector); 72 73 foreach (var branch in branches) 74 { 75 if (Matches(branch.Key, selector)) 76 { 77 return flow.GetValue(branch.Value); 78 } 79 } 80 81 return flow.GetValue(@default); 82 } 83 } 84}