using System.Collections.Generic; namespace Unity.VisualScripting { [TypeIcon(typeof(ISelectUnit))] public abstract class SelectUnit : Unit, ISelectUnit { // Using L instead of Dictionary to allow null key [DoNotSerialize] public List> branches { get; private set; } [Inspectable, Serialize] public List options { get; set; } = new List(); /// /// The value on which to select. /// [DoNotSerialize] [PortLabelHidden] public ValueInput selector { get; private set; } /// /// The output value to return if the selector doesn't match any other option. /// [DoNotSerialize] public ValueInput @default { get; private set; } /// /// The selected value. /// [DoNotSerialize] [PortLabelHidden] public ValueOutput selection { get; private set; } public override bool canDefine => options != null; protected override void Definition() { selection = ValueOutput(nameof(selection), Result).Predictable(); selector = ValueInput(nameof(selector)); Requirement(selector, selection); branches = new List>(); foreach (var option in options) { var key = "%" + option; if (!valueInputs.Contains(key)) { var branch = ValueInput(key).AllowsNull(); branches.Add(new KeyValuePair(option, branch)); Requirement(branch, selection); } } @default = ValueInput(nameof(@default)); Requirement(@default, selection); } protected virtual bool Matches(T a, T b) { return Equals(a, b); } public object Result(Flow flow) { var selector = flow.GetValue(this.selector); foreach (var branch in branches) { if (Matches(branch.Key, selector)) { return flow.GetValue(branch.Value); } } return flow.GetValue(@default); } } }