File size: 2,143 Bytes
18a519f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | using System;
using System.Collections.Generic;
namespace Unity.VisualScripting
{
/// <summary>
/// Selects a value from a set by switching over an enum.
/// </summary>
[UnitCategory("Control")]
[UnitTitle("Select On Enum")]
[UnitShortTitle("Select")]
[UnitSubtitle("On Enum")]
[UnitOrder(7)]
[TypeIcon(typeof(ISelectUnit))]
public sealed class SelectOnEnum : Unit, ISelectUnit
{
[DoNotSerialize]
public Dictionary<object, ValueInput> branches { get; private set; }
/// <summary>
/// The value on which to select.
/// </summary>
[DoNotSerialize]
[PortLabelHidden]
public ValueInput selector { get; private set; }
/// <summary>
/// The selected value.
/// </summary>
[DoNotSerialize]
[PortLabelHidden]
public ValueOutput selection { get; private set; }
[Serialize]
[Inspectable, UnitHeaderInspectable]
[TypeFilter(Enums = true, Classes = false, Interfaces = false, Structs = false, Primitives = false)]
public Type enumType { get; set; }
public override bool canDefine => enumType != null && enumType.IsEnum;
protected override void Definition()
{
branches = new Dictionary<object, ValueInput>();
selection = ValueOutput(nameof(selection), Branch).Predictable();
selector = ValueInput(enumType, nameof(selector));
Requirement(selector, selection);
foreach (var valueByName in EnumUtility.ValuesByNames(enumType))
{
var enumValue = valueByName.Value;
if (branches.ContainsKey(enumValue))
continue;
var branch = ValueInput<object>("%" + valueByName.Key).AllowsNull();
branches.Add(enumValue, branch);
Requirement(branch, selection);
}
}
public object Branch(Flow flow)
{
var selector = flow.GetValue(this.selector, enumType);
return flow.GetValue(branches[selector]);
}
}
}
|