using System.Collections; using System.Linq; namespace Unity.VisualScripting { /// /// Returns the first item in a collection or enumeration. /// [UnitCategory("Collections")] public sealed class LastItem : Unit { /// /// The collection. /// [DoNotSerialize] [PortLabelHidden] public ValueInput collection { get; private set; } /// /// The last item of the collection. /// [DoNotSerialize] [PortLabelHidden] public ValueOutput lastItem { get; private set; } protected override void Definition() { collection = ValueInput(nameof(collection)); lastItem = ValueOutput(nameof(lastItem), First); Requirement(collection, lastItem); } public object First(Flow flow) { var enumerable = flow.GetValue(collection); if (enumerable is IList) { var list = (IList)enumerable; return list[list.Count - 1]; } else { return enumerable.Cast().Last(); } } } }