88 lines
2.6 KiB
C#
88 lines
2.6 KiB
C#
using JetBrains.Annotations;
|
|
using NEG.UI.UnityUi.Buttons;
|
|
using System.Collections.Generic;
|
|
using TMPro;
|
|
using UnityEngine;
|
|
|
|
|
|
namespace NEG.UI.UnityUi
|
|
{
|
|
[PublicAPI]
|
|
public class CarouselList : MonoBehaviour
|
|
{
|
|
/// <summary>
|
|
/// Current option
|
|
/// </summary>
|
|
public string CurrentOption { get; private set; }
|
|
|
|
/// <summary>
|
|
/// Current selected option id
|
|
/// </summary>
|
|
public int CurrentOptionId { get; private set; }
|
|
|
|
[SerializeField] private BaseButton nextButton;
|
|
[SerializeField] private BaseButton prevButton;
|
|
[SerializeField] private TMP_Text currentOptionText;
|
|
|
|
private List<string> options;
|
|
|
|
/// <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;
|
|
}
|
|
|
|
/// <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 Awake()
|
|
{
|
|
nextButton.OnButtonPressed += SelectNextOption;
|
|
prevButton.OnButtonPressed += SelectPrevOption;
|
|
}
|
|
|
|
private void ChangeOption(bool next) => SelectOption((CurrentOptionId + (next ? 1 : -1) + options.Count) % options.Count);
|
|
}
|
|
} |