using System.Collections.Generic; namespace Unity.VisualScripting { [TypeIcon(typeof(IBranchUnit))] public abstract class SwitchUnit : Unit, IBranchUnit { // 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 entry point for the switch. /// [DoNotSerialize] [PortLabelHidden] public ControlInput enter { get; private set; } /// /// The value on which to switch. /// [DoNotSerialize] [PortLabelHidden] public ValueInput selector { get; private set; } /// /// The branch to take if the input value does not match any other option. /// [DoNotSerialize] public ControlOutput @default { get; private set; } public override bool canDefine => options != null; protected override void Definition() { enter = ControlInput(nameof(enter), Enter); selector = ValueInput(nameof(selector)); Requirement(selector, enter); branches = new List>(); foreach (var option in options) { var key = "%" + option; if (!controlOutputs.Contains(key)) { var branch = ControlOutput(key); branches.Add(new KeyValuePair(option, branch)); Succession(enter, branch); } } @default = ControlOutput(nameof(@default)); Succession(enter, @default); } protected virtual bool Matches(T a, T b) { return Equals(a, b); } public ControlOutput Enter(Flow flow) { var selector = flow.GetValue(this.selector); foreach (var branch in branches) { if (Matches(branch.Key, selector)) { return branch.Value; } } return @default; } } }