Neg_Utils/NEG/UI/UnityUi/CarouselList/CarouselList.cs
2024-02-12 21:26:24 +01:00

99 lines
2.9 KiB
C#

using JetBrains.Annotations;
using NEG.UI.UnityUi.Buttons;
using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
namespace NEG.UI.UnityUi
{
[PublicAPI]
public class CarouselList : MonoBehaviour
{
[SerializeField] private BaseButton nextButton;
[SerializeField] private BaseButton prevButton;
[SerializeField] private TMP_Text currentOptionText;
private List<string> options;
/// <summary>
/// Current option
/// </summary>
public string CurrentOption { get; private set; }
/// <summary>
/// Current selected option id
/// </summary>
public int CurrentOptionId { get; private set; }
private void Awake()
{
nextButton.OnButtonPressed += SelectNextOption;
prevButton.OnButtonPressed += SelectPrevOption;
}
private void OnDestroy()
{
nextButton.OnButtonPressed -= SelectNextOption;
prevButton.OnButtonPressed -= SelectPrevOption;
}
public event Action<int> OnSelectedItemChanged;
/// <summary>
/// Sets new options list, automatically first will be selected.
/// </summary>
/// <param name="options">list of options names</param>
public void SetOptions(List<string> options)
{
this.options = options;
SelectOption(0);
}
public void SelectNextOption() => ChangeOption(true);
public void SelectPrevOption() => ChangeOption(false);
/// <summary>
/// Selects option with provided id.
/// </summary>
/// <param name="option">option number</param>
public void SelectOption(int option)
{
if (option < 0 || option >= options.Count)
{
Debug.LogError("Invalid option number");
return;
}
CurrentOptionId = option;
CurrentOption = options[option];
currentOptionText.text = CurrentOption;
OnSelectedItemChanged?.Invoke(CurrentOptionId);
}
/// <summary>
/// Select option with provided value. Use with caution, better use <see cref="SelectOption(int)" />.
/// </summary>
/// <param name="option">option value to select</param>
public void SelectOption(string option)
{
if (options.Count == 0)
{
Debug.LogError("Carousel List cannot be empty when selecting option");
return;
}
int index = options.IndexOf(option);
if (index == -1)
{
Debug.LogError($"Option {option} not found");
return;
}
SelectOption(index);
}
private void ChangeOption(bool next) =>
SelectOption((CurrentOptionId + (next ? 1 : -1) + options.Count) % options.Count);
}
}