using System; using System.Collections; namespace Unity.VisualScripting { /// /// Inserts an item in a list at a specified index. /// [UnitCategory("Collections/Lists")] [UnitSurtitle("List")] [UnitShortTitle("Insert Item")] [UnitOrder(3)] [TypeIcon(typeof(AddListItem))] public sealed class InsertListItem : 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 zero-based index at which to insert the item. /// [DoNotSerialize] public ValueInput index { get; private set; } /// /// The item to insert. /// [DoNotSerialize] public ValueInput item { get; private set; } /// /// The action to execute once the item has been inserted. /// [DoNotSerialize] [PortLabelHidden] public ControlOutput exit { get; private set; } protected override void Definition() { enter = ControlInput(nameof(enter), Insert); listInput = ValueInput(nameof(listInput)); item = ValueInput(nameof(item)); index = ValueInput(nameof(index), 0); listOutput = ValueOutput(nameof(listOutput)); exit = ControlOutput(nameof(exit)); Requirement(listInput, enter); Requirement(item, enter); Requirement(index, enter); Assignment(enter, listOutput); Succession(enter, exit); } public ControlOutput Insert(Flow flow) { var list = flow.GetValue(listInput); var index = flow.GetValue(this.index); var item = flow.GetValue(this.item); if (list is Array) { var resizableList = new ArrayList(list); resizableList.Insert(index, item); flow.SetValue(listOutput, resizableList.ToArray(list.GetType().GetElementType())); } else { list.Insert(index, item); flow.SetValue(listOutput, list); } return exit; } } }