File size: 2,155 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
using System.Collections.Generic;
using UnityEngine;

namespace Unity.VisualScripting
{
    /// <summary>
    /// Selects a value from a set by matching it with an input flow.
    /// </summary>
    [UnitCategory("Control")]
    [UnitTitle("Select On Flow")]
    [UnitShortTitle("Select")]
    [UnitSubtitle("On Flow")]
    [UnitOrder(8)]
    [TypeIcon(typeof(ISelectUnit))]
    public sealed class SelectOnFlow : Unit, ISelectUnit
    {
        [SerializeAs(nameof(branchCount))]
        private int _branchCount = 2;

        [DoNotSerialize]
        [Inspectable, UnitHeaderInspectable("Branches")]
        public int branchCount
        {
            get => _branchCount;
            set => _branchCount = Mathf.Clamp(value, 2, 10);
        }

        [DoNotSerialize]
        public Dictionary<ControlInput, ValueInput> branches { get; private set; }

        /// <summary>
        /// Triggered when any selector is entered.
        /// </summary>
        [DoNotSerialize]
        [PortLabelHidden]
        public ControlOutput exit { get; private set; }

        /// <summary>
        /// The selected value.
        /// </summary>
        [DoNotSerialize]
        [PortLabelHidden]
        public ValueOutput selection { get; private set; }

        protected override void Definition()
        {
            branches = new Dictionary<ControlInput, ValueInput>();

            selection = ValueOutput<object>(nameof(selection));
            exit = ControlOutput(nameof(exit));

            for (int i = 0; i < branchCount; i++)
            {
                var branchValue = ValueInput<object>("value_" + i);
                var branchControl = ControlInput("enter_" + i, (flow) => Select(flow, branchValue));

                Requirement(branchValue, branchControl);
                Assignment(branchControl, selection);
                Succession(branchControl, exit);

                branches.Add(branchControl, branchValue);
            }
        }

        public ControlOutput Select(Flow flow, ValueInput branchValue)
        {
            flow.SetValue(selection, flow.GetValue(branchValue));

            return exit;
        }
    }
}