KSP-Conformal-Decals/Source/ConformalDecals/UI/ColorChannelSlider.cs

79 lines
2.3 KiB
C#
Raw Normal View History

2020-07-21 07:07:18 +00:00
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace ConformalDecals.UI {
public class ColorChannelSlider : MonoBehaviour {
2020-07-23 05:37:16 +00:00
[SerializeField] public ColorPickerController.ChannelUpdateEvent onChannelChanged = new ColorPickerController.ChannelUpdateEvent();
2020-07-21 07:07:18 +00:00
[SerializeField] private float _value;
[SerializeField] private int _channel;
2020-07-23 05:37:16 +00:00
[SerializeField] private bool _hsv;
2020-07-21 07:07:18 +00:00
[SerializeField] private Selectable _textBox;
[SerializeField] private Slider _slider;
[SerializeField] private Image _image;
private bool _ignoreUpdates;
public float Value {
get => _value;
set {
_value = Mathf.Clamp01(value);
UpdateSlider();
UpdateTextbox();
2020-07-23 05:37:16 +00:00
UpdateChannel();
2020-07-21 07:07:18 +00:00
}
}
2020-07-23 05:37:16 +00:00
public void OnColorUpdate(Color rgb, Util.ColorHSV hsv) {
if (_ignoreUpdates) return;
2020-07-21 07:07:18 +00:00
2020-07-23 05:37:16 +00:00
_image.material.SetColor(PropertyIDs._Color, _hsv ? (Color) (Vector4) hsv : rgb);
_value = _hsv ? hsv[_channel] : rgb[_channel];
UpdateSlider();
UpdateTextbox();
}
2020-07-21 07:07:18 +00:00
public void OnTextBoxUpdate(string text) {
if (_ignoreUpdates) return;
if (byte.TryParse(text, out byte byteValue)) {
_value = (float) byteValue / 255;
UpdateSlider();
2020-07-23 05:37:16 +00:00
UpdateChannel();
2020-07-21 07:07:18 +00:00
}
else {
// value is invalid, reset value
UpdateTextbox();
}
}
public void OnSliderUpdate(float value) {
if (_ignoreUpdates) return;
_value = value;
UpdateTextbox();
2020-07-23 05:37:16 +00:00
UpdateChannel();
2020-07-21 07:07:18 +00:00
}
2020-07-23 05:37:16 +00:00
private void UpdateChannel() {
onChannelChanged.Invoke(_value, _channel, _hsv);
2020-07-21 07:07:18 +00:00
}
2020-07-23 05:37:16 +00:00
private void UpdateSlider() {
2020-07-21 07:07:18 +00:00
_ignoreUpdates = true;
_slider.value = _value;
_ignoreUpdates = false;
}
2020-07-23 05:37:16 +00:00
private void UpdateTextbox() {
2020-07-21 07:07:18 +00:00
if (_textBox == null) return;
_ignoreUpdates = true;
((TMP_InputField) _textBox).text = ((byte) (255 * _value)).ToString();
_ignoreUpdates = false;
}
}
}