-
Notifications
You must be signed in to change notification settings - Fork 0
/
BindingButton.cs
92 lines (74 loc) · 2.12 KB
/
BindingButton.cs
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
//
// Cuboid (http://github.com/arjonagelhout/cuboid)
// Copyright (c) 2023 Arjo Nagelhout
//
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using static Cuboid.TransformCommand;
namespace Cuboid.UI
{
[RequireComponent(typeof(Button))]
public abstract class BindingButton<T> : MonoBehaviour
{
protected IBinding<T> _binding;
private Action<T> _onValueChanged;
/// <summary>
/// The associated data with this button, so that the data of the
/// controller can be set to this associated data. e.g.
///
/// MenuController, associated data of this button = Settings
/// Sets the data of the MenuController to Settings.
/// </summary>
[Header("Data Binding")]
[SerializeField] protected T _associatedData;
protected abstract IBinding<T> GetBinding();
private void Awake()
{
_onValueChanged = OnValueChanged;
_button = GetComponent<Button>();
}
protected Button _button;
protected void Start()
{
_binding = GetBinding();
_onValueChanged = OnValueChanged;
_button.ActiveData.OnPressed += OnPressed;
OnValueChanged(_binding.Value); // To make sure it fires the first time
Register();
}
protected abstract void OnValueChanged(T value);
protected virtual void OnPressed()
{
_binding.Value = _associatedData;
}
protected void Register()
{
if (_binding != null)
{
_binding.OnValueChanged += _onValueChanged;
}
}
protected void Unregister()
{
if (_binding != null)
{
_binding.OnValueChanged -= _onValueChanged;
}
}
private void OnEnable()
{
Register();
}
private void OnDisable()
{
Unregister();
}
private void OnDestroy()
{
Unregister();
}
}
}