chip-gameV3/Assets/MNumberStepper.cs

62 lines
1.4 KiB
C#

using System;
using TMPro;
using UnityEngine;
public class MNumberStepper : MonoBehaviour
{
public event Action<int> OnValueChanged;
[SerializeField] private TextMeshProUGUI _valueLabel;
[SerializeField] private CanvasGroup _leftArrow;
[SerializeField] private CanvasGroup _rightArrow;
[SerializeField] float _acceleration;
private float _speed;
private float _lastDirection;
private int _value;
private int _min;
private int _max;
public void Initialize(int value, int min, int max)
{
_value = value;
_min = min;
_max = max;
UpdateView();
}
public void SetDirection(int direction)
{
if (_lastDirection != direction)
ResetSpeed();
_lastDirection = direction;
_speed += direction * _acceleration * Time.deltaTime;
int step = (int)_speed;
int newValue = _value + step;
newValue = Mathf.Clamp(newValue, _min, _max);
bool valueChanged = newValue != _value;
if (valueChanged)
{
_value = newValue;
OnValueChanged?.Invoke(_value);
UpdateView();
}
}
private void UpdateView()
{
_valueLabel.text = _value.ToString();
_leftArrow.alpha = _value == _min ? 0 : 1;
_rightArrow.alpha = _value == _max ? 0 : 1;
}
private void ResetSpeed()
=> _speed = 0;
}