Files
ArrowBeatTap-IOS/Assets/Scripts/LevelManager.cs
T
2026-06-25 15:22:28 +08:00

93 lines
2.6 KiB
C#

using UnityEngine;
using System.Collections.Generic;
using ChillConnect;
public class LevelManager : MonoBehaviour
{
// 单例实例
public static LevelManager Instance { get; private set; }
// 当前加载的关卡配置
public LevelConfig CurrentLevel { get; private set; }
// 关卡文件在 Resources 下的路径前缀
private const string LevelResourcePath = "Levels/lv";
private void Awake()
{
// 单例初始化:保证全局只有一个实例
if (Instance != null && Instance != this)
{
Destroy(gameObject);
return;
}
Instance = this;
// 可选:跨场景不销毁
// DontDestroyOnLoad(gameObject);
}
private void OnDestroy()
{
// 销毁时清空单例引用,防止内存泄漏
if (Instance == this)
{
Instance = null;
}
}
/// <summary>
/// 按关卡ID加载单个关卡配置
/// </summary>
/// <param name="levelId">关卡ID</param>
/// <returns>加载成功返回true</returns>
public bool LoadLevel(int levelId)
{
levelId -= 1;
if (levelId < 0)
{
Debug.LogError("关卡ID必须大于0");
return false;
}
if (levelId > 500)
{
levelId = 500;
}
TextAsset jsonFile = Resources.Load<TextAsset>($"{LevelResourcePath}{levelId}");
if (jsonFile == null)
{
Debug.LogError($"关卡文件加载失败:{LevelResourcePath}{levelId}");
return false;
}
CurrentLevel = JsonUtility.FromJson<LevelConfig>(jsonFile.text);
if (CurrentLevel == null || CurrentLevel.arrows == null)
{
Debug.LogError($"关卡 {levelId} 配置解析失败");
return false;
}
Debug.Log($"关卡 {levelId} 加载成功:{CurrentLevel.levelName},箭头数:{CurrentLevel.arrows.Count}");
return true;
}
/// <summary>
/// 按完整文件名加载关卡(不含.json后缀)
/// </summary>
public bool LoadLevelByName(string fileName)
{
TextAsset jsonFile = Resources.Load<TextAsset>(fileName);
if (jsonFile == null)
{
Debug.LogError($"关卡文件加载失败:{fileName}");
return false;
}
CurrentLevel = JsonUtility.FromJson<LevelConfig>(jsonFile.text);
return CurrentLevel != null;
}
}