miepzerino
2025-03-29 ad79d9ca49274cc660fc2030a071b24314f0f210
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using UnityEngine;
 
namespace Flexalon.Samples
{
    // Changes the material or text color of each child to create a gradient.
    [ExecuteAlways, AddComponentMenu("Flexalon Samples/Flexalon Color Gradient")]
    public class FlexalonColorGradient : MonoBehaviour
    {
        // First color of the gradient.
        [SerializeField]
        private Color _color1;
        public Color Color1
        {
            get => _color1;
            set
            {
                _color1 = value;
                UpdateColors(_node);
            }
        }
 
        // Last color of the gradient.
        [SerializeField]
        private Color _color2;
        public Color Color2
        {
            get => _color2;
            set
            {
                _color2 = value;
                UpdateColors(_node);
            }
        }
 
        // Should update colors when layout changes?
        [SerializeField]
        private bool _runOnLayoutChange;
        public bool RunOnLayoutChange
        {
            get => _runOnLayoutChange;
            set
            {
                _runOnLayoutChange = value;
                UpdateRunOnLayoutChange();
            }
        }
 
        private FlexalonNode _node;
 
        void OnEnable()
        {
            _node = Flexalon.GetOrCreateNode(gameObject);
            UpdateRunOnLayoutChange();
            UpdateColors(_node);
        }
 
        void UpdateRunOnLayoutChange()
        {
            _node.ResultChanged -= UpdateColors;
            if (_runOnLayoutChange)
            {
                _node.ResultChanged += UpdateColors;
            }
        }
 
        void OnDisable()
        {
            _node.ResultChanged -= UpdateColors;
        }
 
        private void UpdateColors(FlexalonNode node)
        {
            foreach (Transform child in transform)
            {
                var color = Color.Lerp(_color1, _color2, (float)(child.GetSiblingIndex()) / transform.childCount);
#if UNITY_TMPRO
                if (child.TryGetComponent<TMPro.TMP_Text>(out var text))
                {
                    text.color = color;
                } else
#endif
#if UNITY_UI
                if (child.TryGetComponent<UnityEngine.UI.Graphic>(out var graphic))
                {
                    graphic.color = color;
                } else
#endif
                if (child.TryGetComponent<FlexalonDynamicMaterial>(out var tdm))
                {
                    tdm.SetColor(color);
                }
            }
        }
    }
}