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