70 lines
2.2 KiB
C#
70 lines
2.2 KiB
C#
using System.IO;
|
|
using UnityEngine;
|
|
|
|
public class SongDataManager : MonoBehaviour
|
|
{
|
|
// ���� JSON �ļ���Ŀ¼·��
|
|
private string jsonDirectory;
|
|
|
|
[Header("Settings")]
|
|
public bool autoSaveOnStart = false; // 默认关闭,仅在需要同步数据时手动开启
|
|
|
|
void Start()
|
|
{
|
|
// 获取持久化存储路径,并在该目录下创建 "SongDataJson" 文件夹
|
|
jsonDirectory = Path.Combine(Application.persistentDataPath, "SongDataJson");
|
|
|
|
// 如果目录不存在,则创建目录
|
|
if (!Directory.Exists(jsonDirectory))
|
|
{
|
|
Directory.CreateDirectory(jsonDirectory);
|
|
Debug.Log("创建 JSON 存储目录: " + jsonDirectory);
|
|
}
|
|
|
|
// 只有开启了 autoSaveOnStart 且在编辑器模式下才自动执行
|
|
if (autoSaveOnStart)
|
|
{
|
|
StartCoroutine(SaveAllSongDataToJsonRoutine());
|
|
}
|
|
}
|
|
|
|
public void TriggerSaveAllSongs()
|
|
{
|
|
StartCoroutine(SaveAllSongDataToJsonRoutine());
|
|
}
|
|
|
|
System.Collections.IEnumerator SaveAllSongDataToJsonRoutine()
|
|
{
|
|
// 从 Resources 文件夹下的 "song_songIndex" 子目录加载所有 SongData 资源
|
|
SongData[] allSongData = Resources.LoadAll<SongData>("song_songIndex");
|
|
|
|
if (allSongData.Length == 0)
|
|
{
|
|
Debug.LogWarning("未在 Resources/song_songIndex 找到任何 SongData 资源。");
|
|
yield break;
|
|
}
|
|
|
|
Debug.Log($"开始异步保存 {allSongData.Length} 个歌曲数据...");
|
|
|
|
// 遍历每个 SongData 资源
|
|
for (int i = 0; i < allSongData.Length; i++)
|
|
{
|
|
SongData song = allSongData[i];
|
|
// 使用 SongDataSerializable 将 SongData 转换为可序列化对象
|
|
SongDataSerializable jsonData = new SongDataSerializable(song);
|
|
string json = JsonUtility.ToJson(jsonData, true);
|
|
|
|
string filePath = Path.Combine(jsonDirectory, song.songID + ".json");
|
|
File.WriteAllText(filePath, json);
|
|
|
|
// 每处理 5 个文件等待一帧,防止主线程卡死
|
|
if (i % 5 == 0)
|
|
{
|
|
yield return null;
|
|
}
|
|
}
|
|
|
|
Debug.Log("所有 JSON 文件保存完毕。");
|
|
}
|
|
}
|