using System; using System.Collections; namespace Unity.VisualScripting { /// /// Adds an item to a list. /// [UnitCategory("Collections/Lists")] [UnitSurtitle("List")] [UnitShortTitle("Add Item")] [UnitOrder(2)] public sealed class AddListItem : Unit { /// /// The entry point for the node. /// [DoNotSerialize] [PortLabelHidden] public ControlInput enter { get; private set; } /// /// The list. /// [DoNotSerialize] [PortLabel("List")] [PortLabelHidden] public ValueInput listInput { get; private set; } /// /// The list with the added element. /// Note that the input list is modified directly and then returned, /// except if it is an array, in which case a new array with /// the added element is returned instead. /// [DoNotSerialize] [PortLabel("List")] [PortLabelHidden] public ValueOutput listOutput { get; private set; } /// /// The item to add. /// [DoNotSerialize] [PortLabelHidden] public ValueInput item { get; private set; } /// /// The action to execute once the item has been added. /// [DoNotSerialize] [PortLabelHidden] public ControlOutput exit { get; private set; } protected override void Definition() { enter = ControlInput(nameof(enter), Add); listInput = ValueInput(nameof(listInput)); item = ValueInput(nameof(item)); listOutput = ValueOutput(nameof(listOutput)); exit = ControlOutput(nameof(exit)); Requirement(listInput, enter); Requirement(item, enter); Assignment(enter, listOutput); Succession(enter, exit); } public ControlOutput Add(Flow flow) { var list = flow.GetValue(listInput); var item = flow.GetValue(this.item); if (list is Array) { var resizableList = new ArrayList(list); resizableList.Add(item); flow.SetValue(listOutput, resizableList.ToArray(list.GetType().GetElementType())); } else { list.Add(item); flow.SetValue(listOutput, list); } return exit; } } }