三国卡牌客户端基础资源仓库
yyl
2025-05-13 e30e257ab8fcec3161337db973d0d1e6f2ce702e
Assets/Editor/ConfigGen/ConfigGenerater.cs
@@ -3,7 +3,6 @@
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
@@ -15,11 +14,6 @@
    // 常量定义
    private const string ConfigsPath = "Assets/Scripts/Main/Config/Configs";
    private const string ConfigManagerPath = "Assets/Scripts/Main/Manager/ConfigManager.cs";
    private const string ConfigBasePattern = @"public\s+class\s+(\w+)\s*:\s*ConfigBase\s*<";
    // 正则表达式模式 - 更新以匹配新的ConfigManager结构
    private static readonly Regex LoadConfigsRegex = new Regex(@"protected\s+async\s+UniTask\s+LoadConfigs\(\)\s*\{[^\}]*\}", RegexOptions.Compiled | RegexOptions.Singleline);
    private static readonly Regex ReleaseRegex = new Regex(@"public\s+override\s+void\s+Release\(\)\s*\{[^\}]*\}", RegexOptions.Compiled | RegexOptions.Singleline);
    
    /// <summary>
    /// 生成配置管理器菜单项
@@ -31,12 +25,6 @@
        {
            // 获取所有配置类
            List<string> configClasses = GetAllConfigClasses();
            // if (configClasses.Count == 0)
            // {
            //     Debug.LogWarning("未找到任何配置类!请确保配置类继承自ConfigBase<T>并位于正确的目录中。");
            //     return;
            // }
            
            // 生成配置管理器代码
            GenerateConfigManager(configClasses);
@@ -70,18 +58,18 @@
        
        try
        {
            // 获取所有C#文件并解析配置类
            return Directory.GetFiles(fullConfigsPath, "*.cs", SearchOption.TopDirectoryOnly)
                .Select(file => new {
                    Path = file,
                    Content = File.ReadAllText(file)
                })
                .Select(file => {
                    Match match = Regex.Match(file.Content, ConfigBasePattern);
                    return match.Success ? match.Groups[1].Value : null;
                })
                .Where(className => !string.IsNullOrEmpty(className))
                .ToList();
            List<string> configClasses = new List<string>();
            // 获取所有C#文件
            string[] files = Directory.GetFiles(fullConfigsPath, "*.cs", SearchOption.TopDirectoryOnly);
            for (int i = 0; i < files.Length; i++)
            {
                string file = files[i];
                configClasses.Add(Path.GetFileNameWithoutExtension(file));
            }
            return configClasses;
        }
        catch (Exception ex)
        {
@@ -99,47 +87,70 @@
        // 获取配置管理器的完整路径
        string fullConfigManagerPath = Path.Combine(Application.dataPath, ConfigManagerPath.Replace("Assets/", ""));
        
        // 检查文件是否存在
        if (!File.Exists(fullConfigManagerPath))
        {
            Debug.LogError($"配置管理器文件不存在: {fullConfigManagerPath}");
            return;
        }
        try
        {
            // 读取原始文件内容
            string originalContent = File.ReadAllText(fullConfigManagerPath);
            // 生成新方法内容
            string loadConfigsMethod = GenerateLoadConfigsMethod(configClasses);
            string releaseMethod = GenerateReleaseMethod(configClasses);
            // 替换方法
            string newContent = LoadConfigsRegex.Replace(originalContent, loadConfigsMethod);
            newContent = ReleaseRegex.Replace(newContent, releaseMethod);
            // 生成完整的配置管理器代码
            string configManagerCode = GenerateFullConfigManagerCode(configClasses);
            
            // 写入文件
            File.WriteAllText(fullConfigManagerPath, newContent);
            File.WriteAllText(fullConfigManagerPath, configManagerCode);
            
            Debug.Log($"成功更新配置管理器: {fullConfigManagerPath}");
            Debug.Log($"成功生成配置管理器: {fullConfigManagerPath}");
        }
        catch (Exception ex)
        {
            Debug.LogError($"更新配置管理器文件时发生错误: {ex.Message}");
            Debug.LogError($"生成配置管理器文件时发生错误: {ex.Message}");
        }
    }
    
    /// <summary>
    /// 生成LoadConfigs方法
    /// 生成完整的配置管理器代码
    /// </summary>
    /// <param name="configClasses">配置类列表</param>
    /// <returns>生成的方法代码</returns>
    private static string GenerateLoadConfigsMethod(List<string> configClasses)
    /// <returns>完整的配置管理器代码</returns>
    private static string GenerateFullConfigManagerCode(List<string> configClasses)
    {
        StringBuilder sb = new StringBuilder();
        
        sb.AppendLine("protected async UniTask LoadConfigs()");
        // 添加命名空间引用
        sb.AppendLine("using System;");
        sb.AppendLine("using System.Collections.Generic;");
        sb.AppendLine("using UnityEngine;");
        sb.AppendLine("using Cysharp.Threading.Tasks;");
        sb.AppendLine("using System.Reflection;");
        sb.AppendLine();
        sb.AppendLine();
        sb.AppendLine("public class ConfigManager : ManagerBase<ConfigManager>");
        sb.AppendLine("{");
        // 添加属性和字段
        sb.AppendLine("    public bool isLoadFinished");
        sb.AppendLine("    {");
        sb.AppendLine("        get;");
        sb.AppendLine("        private set;");
        sb.AppendLine("    }");
        sb.AppendLine();
        sb.AppendLine("    private float loadingProgress = 0f;");
        sb.AppendLine();
        // 添加初始化方法
        sb.AppendLine("    public override void Init()");
        sb.AppendLine("    {");
        sb.AppendLine("        base.Init();");
        sb.AppendLine("        InitConfigs();");
        sb.AppendLine("    }");
        sb.AppendLine();
        // 添加配置初始化方法
        sb.AppendLine("    public virtual async UniTask InitConfigs()");
        sb.AppendLine("    {");
        sb.AppendLine("        // 加载配置文件");
        sb.AppendLine("        await LoadConfigs();");
        sb.AppendLine("    }");
        sb.AppendLine();
        // 添加LoadConfigs方法
        sb.AppendLine("    protected async UniTask LoadConfigs()");
        sb.AppendLine("    {");
        sb.AppendLine("        loadingProgress = 0f;");
        sb.AppendLine("        isLoadFinished = false;");
@@ -151,7 +162,7 @@
        {
            sb.AppendLine($"        int totalConfigs = {configClasses.Count};");
            
            // 方法1:使用数组和循环加载配置
            // 使用数组和循环加载配置
            sb.AppendLine("        Type[] configTypes = new Type[] {");
            for (int i = 0; i < configClasses.Count; i++)
            {
@@ -167,15 +178,19 @@
            sb.AppendLine("            loadingProgress = (float)(i + 1) / totalConfigs;");
            sb.AppendLine("        }");
        }
        else
        {
            Debug.LogError("没有找到配置类 : " + configClasses.Count);
        }
        
        sb.AppendLine();
        sb.AppendLine("        // 加载完成后设置isLoadFinished为true");
        sb.AppendLine("        loadingProgress = 1f;");
        sb.AppendLine("        isLoadFinished = true;");
        sb.AppendLine("    }");
        sb.AppendLine();
        
        // 添加LoadConfigByType方法
        sb.AppendLine();
        sb.AppendLine("    private async UniTask LoadConfigByType(Type configType)");
        sb.AppendLine("    {");
        sb.AppendLine("        string configName = configType.Name;");
@@ -205,20 +220,62 @@
        sb.AppendLine("            Debug.LogError($\"找不到配置文件: {configName}\");");
        sb.AppendLine("        }");
        sb.AppendLine("    }");
        sb.AppendLine();
        
        return sb.ToString();
    }
    /// <summary>
    /// 生成Release方法
    /// </summary>
    /// <param name="configClasses">配置类列表</param>
    /// <returns>生成的方法代码</returns>
    private static string GenerateReleaseMethod(List<string> configClasses)
    {
        StringBuilder sb = new StringBuilder();
        // 添加泛型LoadConfig方法
        sb.AppendLine("    private async UniTask LoadConfig<T>() where T : class");
        sb.AppendLine("    {");
        sb.AppendLine("        string configName = typeof(T).Name;");
        sb.AppendLine();
        sb.AppendLine("        TextAsset textAsset = await ResManager.Instance.LoadAsset<TextAsset>(\"Config\", configName);");
        sb.AppendLine("        if (textAsset != null)");
        sb.AppendLine("        {");
        sb.AppendLine("            string[] lines = textAsset.text.Split('\\n');");
        sb.AppendLine("            var methodInfo = typeof(T).GetMethod(\"Init\", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);");
        sb.AppendLine("            if (methodInfo != null)");
        sb.AppendLine("            {");
        sb.AppendLine("                methodInfo.Invoke(null, new object[] { lines });");
        sb.AppendLine("                // 设置初始化标志");
        sb.AppendLine("                var isInitField = typeof(T).GetField(\"isInit\", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);");
        sb.AppendLine("                if (isInitField != null)");
        sb.AppendLine("                {");
        sb.AppendLine("                    isInitField.SetValue(null, true);");
        sb.AppendLine("                }");
        sb.AppendLine("                Debug.Log($\"加载配置: {typeof(T).Name} 成功\");");
        sb.AppendLine("            }");
        sb.AppendLine("            else");
        sb.AppendLine("            {");
        sb.AppendLine("                Debug.LogError($\"配置类 {typeof(T).Name} 没有静态Init方法\");");
        sb.AppendLine("            }");
        sb.AppendLine("        }");
        sb.AppendLine("        else");
        sb.AppendLine("        {");
        sb.AppendLine("            Debug.LogError($\"找不到配置文件: {configName}\");");
        sb.AppendLine("        }");
        sb.AppendLine("    }");
        sb.AppendLine();
        
        sb.AppendLine("public override void Release()");
        // 添加GetLoadingProgress方法
        sb.AppendLine("    public float GetLoadingProgress()");
        sb.AppendLine("    {");
        sb.AppendLine("        return loadingProgress;");
        sb.AppendLine("    }");
        sb.AppendLine();
        // 添加ClearConfigDictionary方法
        sb.AppendLine("    private void ClearConfigDictionary<T>() where T : class");
        sb.AppendLine("    {");
        sb.AppendLine("        // 重置 T 初始化状态");
        sb.AppendLine("        var isInitField = typeof(T).GetField(\"isInit\", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);");
        sb.AppendLine("        if (isInitField != null)");
        sb.AppendLine("        {");
        sb.AppendLine("            isInitField.SetValue(null, false);");
        sb.AppendLine("        }");
        sb.AppendLine("    }");
        sb.AppendLine();
        // 添加Release方法
        sb.AppendLine("    public override void Release()");
        sb.AppendLine("    {");
        
        if (configClasses.Count > 0)
@@ -237,6 +294,9 @@
        
        sb.AppendLine("    }");
        
        // 结束类定义
        sb.AppendLine("}");
        return sb.ToString();
    }
}