A game about forced loneliness, made by TACStudios
1using System;
2using System.Collections.Generic;
3
4namespace Unity.VisualScripting
5{
6 /// <summary>
7 /// Branches flow by switching over an enum.
8 /// </summary>
9 [UnitCategory("Control")]
10 [UnitTitle("Switch On Enum")]
11 [UnitShortTitle("Switch")]
12 [UnitSubtitle("On Enum")]
13 [UnitOrder(3)]
14 [TypeIcon(typeof(IBranchUnit))]
15 public sealed class SwitchOnEnum : Unit, IBranchUnit
16 {
17 [DoNotSerialize]
18 public Dictionary<Enum, ControlOutput> branches { get; private set; }
19
20 [Serialize]
21 [Inspectable, UnitHeaderInspectable]
22 [TypeFilter(Enums = true, Classes = false, Interfaces = false, Structs = false, Primitives = false)]
23 public Type enumType { get; set; }
24
25 /// <summary>
26 /// The entry point for the switch.
27 /// </summary>
28 [DoNotSerialize]
29 [PortLabelHidden]
30 public ControlInput enter { get; private set; }
31
32 /// <summary>
33 /// The enum value on which to switch.
34 /// </summary>
35 [DoNotSerialize]
36 [PortLabelHidden]
37 public ValueInput @enum { get; private set; }
38
39 public override bool canDefine => enumType != null && enumType.IsEnum;
40
41 protected override void Definition()
42 {
43 branches = new Dictionary<Enum, ControlOutput>();
44
45 enter = ControlInput(nameof(enter), Enter);
46
47 @enum = ValueInput(enumType, nameof(@enum));
48
49 Requirement(@enum, enter);
50
51 foreach (var valueByName in EnumUtility.ValuesByNames(enumType))
52 {
53 var enumName = valueByName.Key;
54 var enumValue = valueByName.Value;
55
56 // Just like in C#, duplicate switch labels for the same underlying value is prohibited
57 if (!branches.ContainsKey(enumValue))
58 {
59 var branch = ControlOutput("%" + enumName);
60
61 branches.Add(enumValue, branch);
62
63 Succession(enter, branch);
64 }
65 }
66 }
67
68 public ControlOutput Enter(Flow flow)
69 {
70 var @enum = (Enum)flow.GetValue(this.@enum, enumType);
71
72 if (branches.ContainsKey(@enum))
73 {
74 return branches[@enum];
75 }
76 else
77 {
78 return null;
79 }
80 }
81 }
82}