92 lines
3.0 KiB
C#
92 lines
3.0 KiB
C#
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
using TMPro;
|
|
|
|
public class SongSelectUI : MonoBehaviour
|
|
{
|
|
public SongList songList; // 存储歌曲列表的 ScriptableObject
|
|
public GameObject songButtonPrefab; // 歌曲按钮的 Prefab (Button)
|
|
public Transform contentPanel; // 滚动视图的 Content 面板
|
|
|
|
void Start()
|
|
{
|
|
if (songList == null || songButtonPrefab == null || contentPanel == null)
|
|
{
|
|
Debug.LogError("请在 Inspector 中分配所有字段!");
|
|
return;
|
|
}
|
|
|
|
DisplaySongs();
|
|
}
|
|
|
|
// 显示所有歌曲
|
|
void DisplaySongs()
|
|
{
|
|
// 清空现有按钮
|
|
foreach (Transform child in contentPanel)
|
|
{
|
|
Destroy(child.gameObject);
|
|
}
|
|
|
|
// 为每首歌曲创建一个按钮
|
|
foreach (SongData song in songList.songs)
|
|
{
|
|
GameObject songButtonObj = Instantiate(songButtonPrefab, contentPanel);
|
|
songButtonObj.transform.SetParent(contentPanel, false); // 确保 UI 结构正确
|
|
|
|
// 获取 SongButton 组件
|
|
SongButton songButton = songButtonObj.GetComponent<SongButton>();
|
|
if (songButton != null)
|
|
{
|
|
// 调用 SetButtonData 赋值
|
|
songButton.SetButtonData(song.songName, song.personalRecord, song.difficultyID, song.illustration, song.songID);
|
|
Debug.Log(" SetButtonData 被调用,songID: " + song.songID);
|
|
}
|
|
else
|
|
{
|
|
Debug.LogError(" SongButton 组件未找到!");
|
|
}
|
|
|
|
// **获取组件**
|
|
Image songImage = songButtonObj.GetComponentInChildren<Image>(); // 获取图片组件
|
|
TMP_Text[] texts = songButtonObj.GetComponentsInChildren<TMP_Text>();
|
|
|
|
if (songImage != null && song.illustration != null)
|
|
{
|
|
songImage.sprite = song.illustration; // 设置歌曲图片
|
|
songImage.enabled = true;
|
|
Debug.Log(" 设置图片:" + song.songName);
|
|
}
|
|
else
|
|
{
|
|
Debug.LogWarning(" Illustration 为空:" + song.songName);
|
|
}
|
|
|
|
if (texts.Length >= 4)
|
|
{
|
|
texts[0].text = song.songName;
|
|
texts[1].text = "Record : " + song.personalRecord;
|
|
texts[3].text = "" + song.difficultyID;
|
|
texts[2].text = "SongID : " + song.songID.ToString();
|
|
Debug.Log(" 设置文本:" + song.songName);
|
|
}
|
|
else
|
|
{
|
|
Debug.LogWarning("TextMeshPro 组件未找到");
|
|
}
|
|
|
|
// **添加按钮事件**
|
|
Button button = songButtonObj.GetComponent<Button>();
|
|
button.onClick.AddListener(() => songButton.OnSongButtonClick());
|
|
}
|
|
}
|
|
|
|
|
|
// 处理点击事件
|
|
void OnSongButtonClicked(SongData song)
|
|
{
|
|
|
|
Debug.Log("🎵 选择歌曲:" + song.songName);
|
|
}
|
|
}
|