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

SwitchUnit.cs 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System.Collections.Generic;
  2. namespace Unity.VisualScripting
  3. {
  4. [TypeIcon(typeof(IBranchUnit))]
  5. public abstract class SwitchUnit<T> : Unit, IBranchUnit
  6. {
  7. // Using L<KVP> instead of Dictionary to allow null key
  8. [DoNotSerialize]
  9. public List<KeyValuePair<T, ControlOutput>> branches { get; private set; }
  10. [Inspectable, Serialize]
  11. public List<T> options { get; set; } = new List<T>();
  12. /// <summary>
  13. /// The entry point for the switch.
  14. /// </summary>
  15. [DoNotSerialize]
  16. [PortLabelHidden]
  17. public ControlInput enter { get; private set; }
  18. /// <summary>
  19. /// The value on which to switch.
  20. /// </summary>
  21. [DoNotSerialize]
  22. [PortLabelHidden]
  23. public ValueInput selector { get; private set; }
  24. /// <summary>
  25. /// The branch to take if the input value does not match any other option.
  26. /// </summary>
  27. [DoNotSerialize]
  28. public ControlOutput @default { get; private set; }
  29. public override bool canDefine => options != null;
  30. protected override void Definition()
  31. {
  32. enter = ControlInput(nameof(enter), Enter);
  33. selector = ValueInput<T>(nameof(selector));
  34. Requirement(selector, enter);
  35. branches = new List<KeyValuePair<T, ControlOutput>>();
  36. foreach (var option in options)
  37. {
  38. var key = "%" + option;
  39. if (!controlOutputs.Contains(key))
  40. {
  41. var branch = ControlOutput(key);
  42. branches.Add(new KeyValuePair<T, ControlOutput>(option, branch));
  43. Succession(enter, branch);
  44. }
  45. }
  46. @default = ControlOutput(nameof(@default));
  47. Succession(enter, @default);
  48. }
  49. protected virtual bool Matches(T a, T b)
  50. {
  51. return Equals(a, b);
  52. }
  53. public ControlOutput Enter(Flow flow)
  54. {
  55. var selector = flow.GetValue<T>(this.selector);
  56. foreach (var branch in branches)
  57. {
  58. if (Matches(branch.Key, selector))
  59. {
  60. return branch.Value;
  61. }
  62. }
  63. return @default;
  64. }
  65. }
  66. }