using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.UI; public class DynamicTable : MonoBehaviour { [Header("Table Settings")] public GameObject tableContainer; // public GameObject headerPrefab; public GameObject rowPrefab; public int columns = 4; public int rows = 10; [TextArea] public string[] tableData; [Header("Style Settings")] public Color headerColor = new Color(0.2f, 0.3f, 0.5f); public Color evenRowColor = new Color(0.9f, 0.9f, 0.9f, 0.5f); public Color oddRowColor = new Color(0.75f, 0.75f, 0.75f, 0.5f); public Color selectedRowColor = new Color(0.5f, 0.7f, 1f, 0.8f); private ScrollRect scrollRect; // private GameObject headerRow; private List tableRows = new List(); private int selectedRow = -1; void Start() { InitializeTable(); GenerateTableData(); } void InitializeTable() { // 确保有ScrollRect组件 scrollRect = tableContainer.GetComponent(); if (scrollRect == null) { scrollRect = tableContainer.AddComponent(); } // 创建内容容器 GameObject content = new GameObject("Content"); RectTransform contentRect = content.AddComponent(); contentRect.SetParent(tableContainer.transform, false); contentRect.anchorMin = Vector2.zero; contentRect.anchorMax = new Vector2(1, 1); contentRect.pivot = new Vector2(0.5f, 1f); contentRect.offsetMin = new Vector2(0, 0); contentRect.offsetMax = new Vector2(0, 0); // 添加垂直布局组 VerticalLayoutGroup verticalLayout = content.AddComponent(); verticalLayout.padding = new RectOffset(5, 5, 5, 5); verticalLayout.spacing = 2f; verticalLayout.childControlHeight = true; verticalLayout.childControlWidth = true; verticalLayout.childForceExpandHeight = false; verticalLayout.childForceExpandWidth = true; // 添加内容尺寸适配 ContentSizeFitter contentFitter = content.AddComponent(); contentFitter.verticalFit = ContentSizeFitter.FitMode.PreferredSize; scrollRect.content = contentRect; } public void GenerateTableData() { // 清除现有行(除了表头) for (int i = tableRows.Count - 1; i >= 0; i--) { Destroy(tableRows[i]); } tableRows.Clear(); // 获取内容容器 Transform content = scrollRect.content; // 生成表格行 for (int rowIdx = 0; rowIdx < rows; rowIdx++) { GameObject row = Instantiate(rowPrefab, content); tableRows.Add(row); // 添加行点击事件 Button rowButton = row.GetComponent