暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

SwitchOnEnum.cs 2.3KB

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