Pagination.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. public class Pagination : MonoBehaviour
  4. {
  5. public int totalPages; // 总页数
  6. public int currentPage; // 总页数
  7. public int visiblePages; // 可见页码数量
  8. public Button firstPageButton;
  9. public Button previousPageButton;
  10. public Button nextPageButton;
  11. public Button lastPageButton;
  12. public GameObject pageButtonPrefab;
  13. public Transform pageButtonsContainer;
  14. void Start()
  15. {
  16. UpdatePagination();
  17. }
  18. public void GoToPage(int page)
  19. {
  20. // 分页逻辑...
  21. }
  22. public void UpdatePagination()
  23. {
  24. int startPage = 1;
  25. int endPage = totalPages;
  26. if (totalPages > visiblePages)
  27. {
  28. startPage = Mathf.Max(1, currentPage - visiblePages / 2);
  29. endPage = Mathf.Min(totalPages, startPage + visiblePages - 1);
  30. if (endPage - startPage < visiblePages - 1)
  31. {
  32. startPage = endPage - visiblePages + 1;
  33. }
  34. if (startPage > 1)
  35. {
  36. firstPageButton.interactable = true;
  37. previousPageButton.interactable = true;
  38. }
  39. else
  40. {
  41. firstPageButton.interactable = false;
  42. previousPageButton.interactable = false;
  43. }
  44. if (endPage < totalPages)
  45. {
  46. lastPageButton.interactable = true;
  47. nextPageButton.interactable = true;
  48. }
  49. else
  50. {
  51. lastPageButton.interactable = false;
  52. nextPageButton.interactable = false;
  53. }
  54. if (startPage > 3)
  55. {
  56. pageButtonsContainer.GetChild(0).GetComponent<Text>().text = "1";
  57. pageButtonsContainer.GetChild(1).GetComponent<Text>().text = "...";
  58. }
  59. if (endPage < totalPages - 1)
  60. {
  61. pageButtonsContainer.GetChild(pageButtonsContainer.childCount - 1).GetComponent<Text>().text = totalPages.ToString();
  62. pageButtonsContainer.GetChild(pageButtonsContainer.childCount - 2).GetComponent<Text>().text = "...";
  63. }
  64. }
  65. // 清除旧的页码按钮
  66. for (int i = 0; i < pageButtonsContainer.childCount; )
  67. {
  68. Destroy(pageButtonsContainer.GetChild(i).gameObject);
  69. }
  70. // 创建新的页码按钮
  71. for (int i = startPage; i <= endPage; i++)
  72. {
  73. Button pageButton = Instantiate(pageButtonPrefab, pageButtonsContainer).GetComponent<Button>();
  74. pageButton.GetComponent<Text>().text = i.ToString();
  75. pageButton.onClick.AddListener(() => GoToPage(i));
  76. }
  77. }
  78. }