namespace DevKit { public class UnityLogger : ILog {… · The Chat Archive
2024-10-23 02:59 UTC Copy response
创建一个 FileWriterLogger 类,该类在子线程中进行文件的读写,并且能够动态设置文件的路径。下面是实现这个功能的一个示例:
csharp Copy code
using System;
using System.IO;
using System.Threading;
using System.Collections.Concurrent;
namespace DevKit
{
public class FileWriterLogger : ILog
{
private int _logLevel = Log.debugLevel;
private string _filePath;
private BlockingCollection<string> _logQueue = new BlockingCollection<string>();
public FileWriterLogger()
{
// Start the logging thread
Thread loggingThread = new Thread(ProcessLogQueue);
loggingThread.IsBackground = true; // Set as a background thread
loggingThread.Start();
}
public void SetLogLevel(int logLevel)
{
_logLevel = logLevel;
}
public int GetLogLevel()
{
return _logLevel;
}
public void SetFilePath(string filePath)
{
_filePath = filePath;
EnsureLogFileExists();
}
private void EnsureLogFileExists()
{
if (!string.IsNullOrEmpty(_filePath) && !File.Exists(_filePath))
{
var fileInfo = new FileInfo(_filePath);
fileInfo.Directory?.Create(); // Create the directory if it doesn't exist
File.Create(_filePath).Close(); // Create the file
}
}
private void ProcessLogQueue()
{
foreach (var logMessage in _logQueue.GetConsumingEnumerable())
{
WriteLogToFile(logMessage);
}
}
private void WriteLogToFile(string message)
{
if (string.IsNullOrEmpty(_filePath))
{
throw new InvalidOperationException("File path is not set.");
}
lock (_filePath) // Ensure that writing to the file is thread-safe
{
File.AppendAllText(_filePath, message + Environment.NewLine);
}
}
public void Error(string message)
{
if (_logLevel >= Log.errorLevel)
{
_logQueue.Add("[ERROR] " + DateTime.Now + ": " + message);
}
}
public void Warning(string message)
{
if (_logLevel >= Log.warningLevel)
{
_logQueue.Add("[WARNING] " + DateTime.Now + ": " + message);
}
}
public void Info(string message)
{
if (_logLevel >= Log.infoLevel)
{
_logQueue.Add("[INFO] " + DateTime.Now + ": " + message);
}
}
public void Debug(string message)
{
if (_logLevel >= Log.debugLevel)
{
_logQueue.Add("[DEBUG] " + DateTime.Now + ": " + message);
}
}
public void Dispose()
{
_logQueue.CompleteAdding();
}
}
}
解释
线程和队列 : 使用 BlockingCollection<string> 作为日志消息的队列,启动一个后台线程,不断从队列中获取日志消息并写入文件。
设置文件路径 : SetFilePath 方法允许动态设置日志文件路径,并调用 EnsureLogFileExists 来保证文件已经创建。
线程安全 : 使用 lock 确保文件写操作的线程安全。
日志等级 : 根据日志级别决定哪些消息被记录。
资源清理 : 用 Dispose 方法完成日志消息队列,并停止日志处理线程。
务必根据你的应用程序的实际需要调整代码,例如实现 ILog 接口的定义和处理异常的策略等。
在子线程中进行文件的创建 以及 长期持有文件的写入stream从而提高写文件的性能,检测应用退出时再关闭子线程的文件写入句柄
Assistant2024-10-23 03:03 UTC Copy response
为了提高文件写入的性能,可以在子线程中长期持有文件写入的流,并在程序退出时关闭。下面是一个示例实现:
c# bool 多线程使用会有问题么,是原子操作么
Assistant2024-10-23 03:11 UTC Copy response
在 C# 中,对 bool 类型的读和写操作是线程安全的,即它们是原子操作。按照 C# 的内存模型,基本数据类型(如 bool、int、float)的读取和写入,大小不超过处理器字长(通常是 32 位或 64 位)的整型数据,都能够被保证是原子性操作。这意味着单次的读或写 bool 类型的值不需要额外的同步,并且不会被中断或被部分执行。
但是,重要的是理解一些关键点:
原子性限制 : 原子性只适用于单次的读或写操作。如果你需要保证一组操作的原子性(例如,先读一个值,再根据该值做出决定然后写入一个新值),那么这组操作不是原子的,你需要使用同步机制(例如 lock)来保护这样的操作。
内存可见性问题 : 即使单词操作是原子的,跨线程的可见性问题仍然存在。一个线程对一个 bool 值的变更可能不会立即对其他线程可见。为了确保一个线程对变量的变更对另一个线程立即可见,你可以使用 volatile 关键字或者其他同步机制。
csharp Copy code
private volatile bool _flag;
使用 volatile 确保当一个线程写入 _flag 时,结果对另一个读取 _flag 的线程立即可见。
典型用法 :
如果你只是想使用一个 bool 变量来实现简单的线程间信号机制,比如表示某个线程应该终止,你可以使用 volatile 关键字。
如果需要在多线程环境下进行更复杂的操作(比如基于 bool 状态进行其他复杂的逻辑决策),则可能需要使用锁或其他同步原语。
综上所述,如果仅仅是对 bool 变量的简单读写操作,那么它是线程安全的。但如果涉及到复杂的操作或需要跨线程保证状态的一致性和可见性,则可能需要使用 volatile 或同步机制来处理。
在unity工程中,有没有办法把所有的Debug.Log 通过hock之类的方式 自动使用自定义的Logger来输出日志
Assistant2024-10-23 03:42 UTC Copy response
在 Unity 中,要将所有的 Debug.Log 输出重定向到自定义 Logger 方法,可以使用一些技巧。不过,Unity 本身没有直接支持通过 hook 或类似机制来自动替换 Debug.Log 的功能。因此,需要一些间接的方法来实现这一目标,以下是一些常见的方式:
方法 1: 自定义方法替代 Debug.Log
将所有的 Debug.Log 调用替换为自定义的日志方法。这通常是推荐的做法,因为它明确且易于维护。
csharp Copy code
public static class CustomLogger
{
public static void Log(string message)
{
// 使用自定义的 Logger 记录日志
// 例如写入文件或发送到远程服务器
FileWriterLogger.Instance.Info(message);
// 仍然调用 Unity 的 Debug.Log 以便在控制台显示
Debug.Log(message);
}
public static void LogWarning(string message)
{
// 类似处理警告信息
FileWriterLogger.Instance.Warning(message);
Debug.LogWarning(message);
}
public static void LogError(string message)
{
// 类似处理错误信息
FileWriterLogger.Instance.Error(message);
Debug.LogError(message);
}
}
一旦建立了这个类,你就可以在项目中使用 CustomLogger.Log() 等方法,替换所有的 Debug.Log 调用。
方法 2: 使用编译器指令或脚本重写
如果项目较大且不太现实手动替换,你可以考虑编写一个脚本来自动重写源代码中的 Debug.Log 调用为自定义的方法。这种方式适合于代码量巨大的工程,但需要注意:
正则表达式可以用来匹配并替换代码中的 Debug.Log。
确保在版本控制下进行,以便可以轻松地还原更改。
可能需要手动调整复杂的场景。
方法 3: Hook 不推荐方法
理论上可以通过修改 Unity 引擎的 DLL 或使用反射来 hook Debug.Log,不过这并不被推荐,因为 Unity 的核心 DLL 是内置的,修改它们可能违反使用条款,并导致工程不稳定、无法更新或兼容性问题。
方法 4: 使用自定义定义的 preprocessor directives
你也可以通过 #define 指令自定义日志方法并控制定义:
csharp Copy code
#define USE_CUSTOM_LOGGER
public class Example
{
public void ExampleMethod()
{
#if USE_CUSTOM_LOGGER
CustomLogger.Log("This is a custom log message.");
#else
Debug.Log("This is a standard log message.");
#endif
}
}
这种方法适合有条件地在不同环境中使用不同的日志机制。
注意事项
确保所有的日志记录都集中在一个地方,这样在发生错误时你只有一个地方需要更改。
使用版本控制来安全地尝试和应用此类全局性更改。
通过编写自定义的 Logger 类,你可以灵活地将日志路由到不同的目的地,例如控制台、文件系统、远程服务器等。
考虑使用 Unity 的 EventSystem 或类似的全局事件总线机制进行事件广播。
通过上述方法,尤其是方法 1 中自定义的日志类,可以很好地控制和管理整个项目的日志输出。
那有没有办法让所有使用Unity提供的Debug.Log 都会编译错误 并提示请使用Log.Info
Assistant2024-10-23 03:43 UTC Copy response
为了使所有使用 Unity 提供的 Debug.Log 方法在编译时产生错误,并提示使用 CustomLogger.Log 或 Log.Info,可以使用 C# 的编译器指令以及一些简单的技巧。在 Unity 项目中,你可以通过以下方法来达到这个目的:
方法:使用编译器属性和预处理器指令
你可以使用 #error 预处理指令来强制编译器产生错误。这可以引导开发者避免使用不当的日志方法。不过,C# 不允许直接插入 #error 到外部库方法调用(如 Unity 的 Debug.Log),因此你可能需要在代码中手动添加检查。
方案 1:代码审查和手动检查
可以手动查看代码并添加以下行,以便识别错误的使用:
csharp Copy code
#error "Please use CustomLogger.Log instead of Debug.Log"
这需要开发者在 Debug.Log 行之前手动添加,很明显这种方法对于大型项目或团队来说不够现实。
方案 2:使用自定义分析器或脚本工具
可以编写一个使用 Roslyn 编译器平台的自定义分析器,该分析器能够在发现 Debug.Log 的调用时产生警告或错误。这需要深入了解 Roslyn 和编写自定义的 Roslyn Analyzers。
方案 3:全局查找和替换脚本
在整个项目中使用脚本工具来查找 Debug.Log 调用,并自动替换为自定义的 Log.Info,以下为示意脚本(假设使用某种命令行脚本或编辑器工具):
bash Copy code
# 对于 Linux/macOS
find . -name "*.cs" -exec sed -i 's/Debug\.Log/CustomLogger\.Log/g' {} +
# 对于 Windows,可以使用 PowerShell
Get-ChildItem -Recurse -Include *.cs | ForEach-Object {
(Get-Content $_.FullName) -replace "Debug\.Log", "CustomLogger\.Log" | Set-Content $_.FullName
}
方案 4:使用 Unity 自带的脚本编译警告
虽然 Unity 没有直接支持强制编译时错误的功能,但可以构造编译时警告来提醒开发者:
csharp Copy code
#if UNITY_EDITOR
using UnityEditor;
[InitializeOnLoad]
public class LogChecker
{
static LogChecker()
{
EditorApplication.delayCall += CheckLogUsage;
}
private static void CheckLogUsage()
{
// 理论上,需要扫描代码文件然后判断是否有 Debug.Log
// 由于复杂性及效率问题,简要示例不提供具体实现。
// 使用 Regex 或其他方式来扫描项目代码文件中 Debug.Log 的使用
// 一旦发现 Debug.Log 使用,可以使用 UnityEngine.Debug.LogWarning 或其他方式提示开发者
}
}
#endif
最佳实践
使用方案 1 和 2 来严格强制策略可能不是最优的,你可以选择用方案 3 或方案 4 来进行非侵入式的检查和提示。当项目开发过程中发现 Debug.Log 使用错误是很常见的,因此推荐的方法是教育开发者使用自定义日志系统,同时定期进行代码检查和评审。
编写一个Unity Editor下的工具,来检查Debug.Log的使用,检查所有使用了Debug.Log的地方并提示修改为Log.Info(是否可以使用c#反射等办法快速查找Debug.Log的使用处)
Assistant2024-10-23 03:47 UTC Copy response
在 Unity 中编写一个在 Editor 下运行的工具,来检查代码中所有使用 Debug.Log 的地方,并提供提示以修改为 Log.Info,可以使用 C# 的反射或者更高效的正则表达式来分析脚本源代码。虽然反射对于类型和成员检查很有用,但用于代码文本分析时,静态代码解析更为适合。
下面是一个简单的 Unity Editor 工具示例,通过解析所有 .cs 文件来查找 Debug.Log 的使用,并提示开发者进行更改。
工具实现步骤
创建自定义的 Unity Editor 脚本 :在 Unity 中,你可以创建一个 Editor 脚本来检查项目中的脚本文件。
使用正则表达式解析脚本文件 :读取每个脚本文件,对文件内容进行正则表达式匹配,查找 Debug.Log 的使用。
输出查找到的结果 :在 Unity Editor 的控制台中输出找到的使用位置,并提示开发者进行更改。
以下是代码示例:
csharp Copy code
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text.RegularExpressions;
public class DebugLogChecker : EditorWindow
{
[MenuItem("Tools/Debug.Log Checker")]
public static void ShowWindow()
{
GetWindow(typeof(DebugLogChecker), false, "Debug.Log Checker");
}
private void OnGUI()
{
if (GUILayout.Button("Check for Debug.Log usages"))
{
CheckDebugLogUsages();
}
}
private void CheckDebugLogUsages()
{
// 获取项目中的所有脚本文件
string[] scriptPaths = Directory.GetFiles(Application.dataPath, "*.cs", SearchOption.AllDirectories);
foreach (string scriptPath in scriptPaths)
{
string scriptContent = File.ReadAllText(scriptPath);
// 通过正则表达式查找 Debug.Log 的使用
MatchCollection matches = Regex.Matches(scriptContent, @"\bDebug\.Log\b");
if (matches.Count > 0)
{
string relativePath = "Assets" + scriptPath.Replace(Application.dataPath, "").Replace('\\', '/');
// 提示信息输出到控制台
Debug.LogWarning($"Found {matches.Count} usage(s) of Debug.Log in {relativePath}. Consider replacing with Log.Info.");
foreach (Match match in matches)
{
// 选中并高亮问题文件中的位置
int lineIndex = scriptContent.Substring(0, match.Index).Split('\n').Length;
Debug.LogWarning($"Located at line: {lineIndex} in {relativePath}");
}
}
}
}
}
正则表达式 \bDebug.Log\b 改为查找所有 Debug.Log, Debug.LogXXX
Assistant2024-10-23 04:02 UTC Copy response
要查找所有使用 Debug.Log 以及类似的 Debug.LogWarning, Debug.LogError 和其他类似形式的日志调用,可以使用更通用的正则表达式模式。例如:
Debug.Log
Debug.LogWarning
Debug.LogError
其他可能的 Debug.Log 相关方法
我们需要调整正则表达式来匹配所有这些变体。此示例的正则表达式可以使用:
regex Copy code
\bDebug\.Log\w*\b
此表达式会匹配所有以 Debug.Log 开头,并可能带有其他字符(如 Warning 或 Error)的符号。
以下是调整后的代码示例:
csharp Copy code
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text.RegularExpressions;
public class DebugLogChecker : EditorWindow
{
[MenuItem("Tools/Debug.Log Checker")]
public static void ShowWindow()
{
GetWindow(typeof(DebugLogChecker), false, "Debug.Log Checker");
}
private void OnGUI()
{
if (GUILayout.Button("Check for Debug.Log usages"))
{
CheckDebugLogUsages();
}
}
private void CheckDebugLogUsages()
{
// 获取项目中的所有脚本文件
string[] scriptPaths = Directory.GetFiles(Application.dataPath, "*.cs", SearchOption.AllDirectories);
foreach (string scriptPath in scriptPaths)
{
string scriptContent = File.ReadAllText(scriptPath);
// 搜索所有 Debug.Log 和类似的方法
MatchCollection matches = Regex.Matches(scriptContent, @"\bDebug\.Log\w*\b");
if (matches.Count > 0)
{
string relativePath = "Assets" + scriptPath.Replace(Application.dataPath, "").Replace('\\', '/');
// 提示信息输出到控制台
Debug.LogWarning($"Found {matches.Count} usage(s) of Debug.Log variants in {relativePath}. Consider replacing with Log.Info.");
foreach (Match match in matches)
{
// 选中并高亮问题文件中的位置
int lineIndex = scriptContent.Substring(0, match.Index).Split('\n').Length;
Debug.LogWarning($"Located at line: {lineIndex} in {relativePath}");
}
}
}
}
}
说明
\bDebug\.Log\w*\b :
\b 代表单词边界,确保匹配的是一个完整的词。
Debug\.Log 匹配 Debug.Log。
\w* 匹配零个或多个字母或数字字符,允许匹配 LogWarning、LogError 等。
另一个 \b 确保整个匹配是一个完整的单词。
这样,工具可以识别并标记所有形如 Debug.Log 及其变体的方法调用。通过运行该工具,开发者可以轻松发现和更改代码中相关方法的使用。注意,正则表达式匹配是基于文本的,因此对于非常复杂的嵌套或动态代码,可能需要更复杂的方法来捕获所有变体。
namespace DevKit.Editor
{
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text.RegularExpressions;
code Copy code
public class DebugLogCheckerWindow : EditorWindow
{
[MenuItem("DevKit/Log/DebugLogChecker")]
public static void ShowWindow()
{
GetWindow(typeof(DebugLogCheckerWindow), false, "Debug Log Checker");
}
private void OnGUI()
{
if (GUILayout.Button("Check for Debug.Log usages"))
{
_checkDebugLogUsages();
}
}
private void _checkDebugLogUsages()
{
// 获取项目中的所有脚本文件
string[] scriptPaths = Directory.GetFiles(Application.dataPath, "*.cs", SearchOption.AllDirectories);
foreach (string scriptPath in scriptPaths)
{
string scriptContent = File.ReadAllText(scriptPath);
// 通过正则表达式查找 Debug.Log 的使用
MatchCollection matches = Regex.Matches(scriptContent, @"\bDebug\.Log\w*\b");
if (matches.Count > 0)
{
string relativePath = "Assets" + scriptPath.Replace(Application.dataPath, "").Replace('\\', '/');
// 提示信息输出到控制台
Debug.LogWarning($"Found {matches.Count} usage(s) of Debug.Log in {relativePath}. Consider replacing with Log.Info.");
foreach (Match match in matches)
{
// 选中并高亮问题文件中的位置
int lineIndex = scriptContent.Substring(0, match.Index).Split('\n').Length;
Debug.LogWarning($"Located at line: {lineIndex} in {relativePath}");
}
}
}
}
}
} 修改上述代码,查找完成后显示所有的Script对象
Show full message · 53 lines Assistant2024-10-23 04:03 UTC Copy response
如果你想要在查找完成后在 Unity 编辑器中显示所有包含 Debug.Log 的 Script 对象,你可以将搜索到的结果存储起来,并在 OnGUI 方法中以可视化列表的形式展示出来。这里是对你的工具进一步修改以实现这一功能的代码示例:
csharp Copy code
namespace DevKit.Editor
{
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class DebugLogCheckerWindow : EditorWindow
{
private List<string> resultFiles = new List<string>();
private Vector2 scrollPosition;
[MenuItem("DevKit/Log/DebugLogChecker")]
public static void ShowWindow()
{
GetWindow(typeof(DebugLogCheckerWindow), false, "Debug Log Checker");
}
private void OnGUI()
{
if (GUILayout.Button("Check for Debug.Log usages"))
{
resultFiles.Clear();
_checkDebugLogUsages();
}
if (resultFiles.Count > 0)
{
GUILayout.Label("Scripts with Debug.Log usage:");
scrollPosition = GUILayout.BeginScrollView(scrollPosition);
foreach (var file in resultFiles)
{
if (GUILayout.Button(file))
{
// 选中并高亮在 Project 视图中的文件
var asset = AssetDatabase.LoadAssetAtPath<MonoScript>(file);
if (asset != null)
{
Selection.activeObject = asset;
}
}
}
GUILayout.EndScrollView();
}
else
{
GUILayout.Label("No Debug.Log usages found.");
}
}
private void _checkDebugLogUsages()
{
// 获取项目中的所有脚本文件
string[] scriptPaths = Directory.GetFiles(Application.dataPath, "*.cs", SearchOption.AllDirectories);
foreach (string scriptPath in scriptPaths)
{
string scriptContent = File.ReadAllText(scriptPath);
// 通过正则表达式查找 Debug.Log 的使用
MatchCollection matches = Regex.Matches(scriptContent, @"\bDebug\.Log\w*\b");
if (matches.Count > 0)
{
string relativePath = "Assets" + scriptPath.Replace(Application.dataPath, "").Replace('\\', '/');
// 将找到的文件路径加入结果列表
resultFiles.Add(relativePath);
// 提示信息输出到控制台
Debug.LogWarning($"Found {matches.Count} usage(s) of Debug.Log in {relativePath}. Consider replacing with Log.Info.");
foreach (Match match in matches)
{
// 选中并高亮问题文件中的位置
int lineIndex = scriptContent.Substring(0, match.Index).Split('\n').Length;
Debug.LogWarning($"Located at line: {lineIndex} in {relativePath}");
}
}
}
}
}
}
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace DevKit.Editor
{
public class DebugLogCheckerWindow : EditorWindow
{
private List _resultFiles = new();
private Dictionary<string, StringBuilder> _resultContents = new();
private Vector2 _scrollPosition = Vector2.zero;
code Copy code
private static string[] _excludeDirs = new string[]
{
"Plugins",
"*/Editor"
};
[MenuItem("DevKit/Log/DebugLogChecker")]
public static void ShowWindow()
{
GetWindow(typeof(DebugLogCheckerWindow), false, "Debug Log Checker");
}
private void OnGUI()
{
if (GUILayout.Button("Check for Debug.Log usages"))
{
_resultFiles.Clear();
_checkDebugLogUsages();
}
if (_resultFiles.Count > 0)
{
GUILayout.Label("Scripts with Debug.Log usage:");
_scrollPosition = GUILayout.BeginScrollView(_scrollPosition);
foreach (var file in _resultFiles)
{
if (GUILayout.Button(file))
{
// 选中并高亮在 Project 视图中的文件
var asset = AssetDatabase.LoadAssetAtPath<MonoScript>(file);
if (asset != null)
{
Selection.activeObject = asset;
}
}
}
GUILayout.EndScrollView();
}
else
{
GUILayout.Label("No Debug.Log usages found.");
}
}
private void _checkDebugLogUsages()
{
// 获取项目中的所有脚本文件
string[] scriptPaths = Directory.GetFiles(Application.dataPath, "*.cs", SearchOption.AllDirectories);
foreach (string scriptPath in scriptPaths)
{
string scriptContent = File.ReadAllText(scriptPath);
// 通过正则表达式查找 Debug.Log 的使用
MatchCollection matches = Regex.Matches(scriptContent, @"\bDebug\.Log\w*\b");
if (matches.Count > 0)
{
string relativePath = "Assets" + scriptPath.Replace(Application.dataPath, "").Replace('\\', '/');
// 将找到的文件路径加入结果列表
_resultFiles.Add(relativePath);
// 提示信息输出到控制台
Debug.LogWarning($"Found {matches.Count} usage(s) of Debug.Log in {relativePath}. Consider replacing with Log.Info.");
var resultContent = new StringBuilder();
_resultContents[relativePath] = resultContent;
foreach (Match match in matches)
{
// 选中并高亮问题文件中的位置
int lineIndex = scriptContent.Substring(0, match.Index).Split('\n').Length;
var resultLine = $"Located at line: {lineIndex} in {relativePath}";
resultContent.AppendLine(resultLine);
Debug.LogWarning(resultLine);
}
}
}
}
}
Show full message · 98 lines Assistant2024-10-23 04:13 UTC Copy response
为了解决这两个需求,我们需要对代码进行以下改进:
排除指定目录 :在遍历文件时,跳过 _excludeDirs 中指定的目录(如 "Plugins" 和任何以 "Editor" 为子目录的目录)。
显示每个文件的详细结果内容 :在 GUI 中为每个找到的文件展示其对应的详细匹配结果。
以下是改进后的完整代码:
int lineIndex = scriptContent.Substring(0, match.Index).Split('\n').Length;
var resultLine = $"Located at line: {lineIndex}, {match.Value}";
resultContent.AppendLine(resultLine);
Debug.LogWarning(resultLine); 如何获取匹配到的一行的代码
Assistant2024-10-23 04:17 UTC Copy response
要获取匹配到的 Debug.Log 语句所在的整行代码,可以利用正则表达式和字符串操作来提取具体的行内容。这里提供两种方法实现:通过正则表达式确定整行以及通过字符串操作获取行内容。
通过字符串操作获取行内容
你可以在匹配到的 Debug.Log 所在的行之前和之后进行截取,以下是实现代码:
csharp Copy code
private void _checkDebugLogUsages()
{
string[] scriptPaths = Directory.GetFiles(Application.dataPath, "*.cs", SearchOption.AllDirectories);
foreach (string scriptPath in scriptPaths)
{
if (IsExcludedPath(scriptPath))
{
continue;
}
string scriptContent = File.ReadAllText(scriptPath);
string[] lines = scriptContent.Split('\n'); // 将文件内容按行分割
MatchCollection matches = Regex.Matches(scriptContent, @"\bDebug\.Log\w*\b");
if (matches.Count > 0)
{
string relativePath = "Assets" + scriptPath.Replace(Application.dataPath, "").Replace('\\', '/');
_resultFiles.Add(relativePath);
Debug.LogWarning($"Found {matches.Count} usage(s) of Debug.Log in {relativePath}. Consider replacing with Log.Info.");
var resultContent = new StringBuilder();
_resultContents[relativePath] = resultContent;
foreach (Match match in matches)
{
int lineIndex = scriptContent.Substring(0, match.Index).Split('\n').Length - 1;
string lineContent = lines[lineIndex].Trim(); // 获取具体行内容
var resultLine = $"Located at line: {lineIndex + 1}, {match.Value}. Code: {lineContent}";
resultContent.AppendLine(resultLine);
Debug.LogWarning(resultLine);
}
}
}
}
说明
分割文件内容 :string[] lines = scriptContent.Split('\n'); 将整个脚本内容按行分割为一个数组,这样每个元素就代表源文件中的一行。
行索引调整 :通过 Split('\n').Length - 1 计算行的索引,因为数组是从零开始的,而行号通常是从 1 开始的。
获取行内容 :通过 string lineContent = lines[lineIndex].Trim(); 获取特定行,使用 Trim() 去掉行首尾的多余空白。
通过这种方法,我们可以在控制台以及编辑器窗口中展示每个匹配的 Debug.Log 语句所在行的具体代码,使开发者能够更直观地识别需要修改的部分。
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace DevKit.Editor
{
public class DebugLogCheckerWindow : EditorWindow
{
private List _resultFiles = new();
private Dictionary<string, StringBuilder> _resultContents = new();
private Vector2 _scrollPosition = Vector2.zero;
Show full message · 137 lines Assistant2024-10-23 04:25 UTC Copy response
要完善 _replaceDebugLogUsages 的功能,使其能够替换脚本中的 Debug.Log 调用,可以执行以下步骤:
读取和替换文本内容 :将 Debug.Log 及其变体替换为 Log.Info 或其他自定义日志方法。
更新脚本文件 :将修改后的内容写回到原始脚本文件。
刷新 Unity 编辑器 :在 Unity 中应用这些修改。
以下是改进后的代码示例:
text.text = angle.ToString("0") + "";
上面的C#代码的gc 如何修改才能优化掉
Assistant2024-10-23 06:00 UTC Copy response
在 Unity 中,每当你进行字符串连接或格式化操作时,都可能会导致垃圾收集(GC)开销,这是因为字符串在 C# 中是不可变的。当你对字符串进行操作时,实际上是创建了一个新的字符串对象。
在你提供的代码中,text.text = angle.ToString("0") + ""; 的性能问题主要来源于字符串连接操作(+ ""),尽管在这特定例子中,+ "" 操作是多余的,因为它没有实际增加任何字符。要优化这个代码,从而避免不必要的字符串创建,可以直接使用:
csharp Copy code
text.text = angle.ToString("0");
这样做的好处包括:
避免多余的字符串连接 :去掉 + "",减少不必要的字符串创建,每次 + 操作会创建一个新的字符串对象。
格式化直接使用 :angle.ToString("0") 已经满足了格式化的需求,提供了整形显示(无小数点),因此不需要额外的修饰。
一些其他优化建议:
保持代码简洁可以帮助减轻不必要的内存分配和 GC 负担。在这个具体的示例中,去掉 + "" 是最直接且有效的优化途径。
unity editor , // 绘制dropdown显示所有buildprofilers, 以及当前选择的buildprofiler
Assistant2024-10-23 06:36 UTC Copy response
在 Unity Editor 中,如果你希望创建一个自定义的编辑器窗口或面板来显示所有可用的构建配置文件(build profilings)并允许用户从中选择一个当前使用的构建配置文件,可以使用 EditorWindow 和 EditorGUILayout.Popup 来实现。这种方法可以很方便地创建一个下拉菜单显示和选择构建配置文件(假设这些配置文件是预先定义的)。
这里是一个示例,展示如何构建这样的编辑器工具:
1. 创建一个编辑器窗口:
首先,需要在 Unity 中创建一个自定义编辑器窗口。这个窗口将显示可用的构建配置文件并允许用户选择其中一个。假设你有一个 BuildProfiler 类来表示每个配置文件。
csharp Copy code
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
public class BuildProfilerWindow : EditorWindow
{
private int selectedProfilerIndex = 0;
private List<BuildProfiler> buildProfilers = new List<BuildProfiler>();
private string[] profilerNames;
[MenuItem("Window/Build Profiler")]
public static void ShowWindow()
{
GetWindow<BuildProfilerWindow>("Build Profiler");
}
private void OnEnable()
{
// 假设您有一个方法来获取所有的BuildProfilers
buildProfilers = GetAllBuildProfilers();
profilerNames = new string[buildProfilers.Count];
for (int i = 0; i < buildProfilers.Count; i++)
{
profilerNames[i] = buildProfilers[i].name; // 确保每个BuildProfiler有一个名称
}
}
private void OnGUI()
{
GUILayout.Label("Select a Build Profiler", EditorStyles.boldLabel);
// 显示 Dropdown 选择
selectedProfilerIndex = EditorGUILayout.Popup("Build Profiler", selectedProfilerIndex, profilerNames);
EditorGUILayout.Space();
// 显示当前选中的配置文件的详细信息
if (buildProfilers.Count > 0)
{
DisplayProfilerDetails(buildProfilers[selectedProfilerIndex]);
}
EditorGUILayout.Space();
if (GUILayout.Button("Apply Selected Profiler"))
{
ApplyBuildProfiler(buildProfilers[selectedProfilerIndex]);
}
}
private void DisplayProfilerDetails(BuildProfiler profiler)
{
if (profiler == null) return;
// 示例显示属性,可以根据具体的BuildProfiler属性来调整
EditorGUILayout.LabelField("Details:", EditorStyles.boldLabel);
EditorGUILayout.LabelField("Name: ", profiler.name);
EditorGUILayout.LabelField("Description: ", profiler.description);
// Add more fields as needed
}
private List<BuildProfiler> GetAllBuildProfilers()
{
// 假设你有预定义的BuildProfilers,这里返回一个示例列表
return new List<BuildProfiler>
{
new BuildProfiler("Default", "Default build configuration"),
new BuildProfiler("Optimized", "Optimized for performance"),
new BuildProfiler("Debug", "Debugging enabled")
};
}
private void ApplyBuildProfiler(BuildProfiler profiler)
{
// 在这里执行应用选中的构建配置文件的逻辑
Debug.Log($"Applying Build Profiler: {profiler.name}");
}
}
public class BuildProfiler
{
public string name;
public string description;
public BuildProfiler(string name, string description)
{
this.name = name;
this.description = description;
}
}
unity EditorGUILayout.PropertyField 对于 list 在用户选择数组中某个场景时 会发生不更新新选择的数组元素的问题
Assistant2024-10-23 07:52 UTC Copy response
在 Unity Editor 中使用 EditorGUILayout.PropertyField 来展示和编辑 List<SceneAsset> 时,如果遇到选择场景后不更新数组元素的问题,通常是因为没有正确地处理 Unity 的序列化系统。Unity 的序列化系统对某些类型有限制,尤其是对类型的具体数据使用引用而不是实际值(例如 SceneAsset)。
要确保编辑器面板正确更新,你可以遵循以下步骤:
序列化对象和属性 :确保你的数据结构和编辑器代码使用 SerializedObject 和 SerializedProperty 进行交互。
自定义属性Drawer或Editor :可能需要编写自定义的 PropertyDrawer 或 Editor 来正确处理 SceneAsset,因为直接使用基本的 PropertyField 处理可能不会更新引用。
以下是一个示例代码,展示如何在 Unity 自定义编辑器中处理序列化 List<SceneAsset>:
csharp Copy code
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
[CreateAssetMenu(fileName = "SceneAssetList", menuName = "ScriptableObjects/SceneAssetList", order = 1)]
public class SceneAssetList : ScriptableObject
{
public List<SceneAsset> scenes;
}
[CustomEditor(typeof(SceneAssetList))]
public class SceneAssetListEditor : Editor
{
private SerializedProperty scenesProperty;
private void OnEnable()
{
// 获取 scenes 属性的 SerializedProperty
scenesProperty = serializedObject.FindProperty("scenes");
}
public override void OnInspectorGUI()
{
// 更新 serializedObject
serializedObject.Update();
// 显示列表头部
EditorGUILayout.PropertyField(scenesProperty, new GUIContent("Scenes"), true);
// 应用修改
serializedObject.ApplyModifiedProperties();
}
}
说明
ScriptableObject : 示例中创建了一个 ScriptableObject 来存储场景资产列表。SceneAssetList 包含一个 List<SceneAsset> 以管理场景资产。
自定义编辑器 : 使用 CustomEditor 对 SceneAssetList 进行自定义编辑器扩展。
SerializedProperty : 使用 SerializedProperty 来访问和修改 List<SceneAsset>,这使得属性可以通过 Unity 的序列化系统来处理更新和保存。
更新和应用 :
在 OnInspectorGUI 方法中,使用 serializedObject.Update() 来刷新属性。
使用 EditorGUILayout.PropertyField 正确处理 SerializedProperty 的显示和编辑。
最后使用 serializedObject.ApplyModifiedProperties() 来应用任何修改。
通过这种方式,你可以确保 List<SceneAsset> 的内容在修改后可以正确更新和保存。如果由于复杂性或特殊的需求导致这种方式仍无法满足,你可以考虑实现一个自定义的 PropertyDrawer 更精细地控制编辑行为。
unity delete a folder asset
Assistant2024-10-23 08:36 UTC Copy response
在 Unity 中删除文件夹可以通过多种方法实现,其中包括使用 Unity 的编辑器界面手动删除,以及通过脚本来自动化删除操作。
在 Unity 编辑器中手动删除
打开项目窗口 :导航到 Unity Editor 的 Project 窗口。
选择文件夹 :找到你想要删除的文件夹,单击选中它。
删除文件夹 :
你可以右键单击选中的文件夹,选择 Delete。
或者,直接按 Delete 键来删除文件夹。
确认删除 :Unity 会弹出一个确认框,确认删除后,Unity 将删除该文件夹及其内容。
使用脚本自动删除文件夹
有时候你可能需要通过脚本自动删除一个文件夹,比如在自定义工具或构建脚本中。不仅仅是从文件系统上移除,还需要刷新 Unity 的资产数据库。你可以使用 FileUtil 或 AssetDatabase 提供的方法。
csharp Copy code
using UnityEditor;
using UnityEngine;
public class DeleteFolderExample
{
[MenuItem("Tools/Delete Folder Example")]
public static void DeleteFolder()
{
// 要删除的文件夹的相对路径,从 "Assets" 开始
string folderPath = "Assets/YourFolderName";
if (AssetDatabase.IsValidFolder(folderPath))
{
// 删除文件夹并刷新资产数据库
AssetDatabase.DeleteAsset(folderPath);
AssetDatabase.Refresh();
Debug.Log($"Deleted folder: {folderPath}");
}
else
{
Debug.LogWarning($"Folder not found: {folderPath}");
}
}
}
说明
路径注意 :folderPath 是相对于项目的 Assets 目录的路径。如果你的项目结构是 Assets/Resources/YourFolderName,那么 folderPath 应为 "Assets/Resources/YourFolderName"。
检查文件夹存在性 :在删除之前,我们使用 AssetDatabase.IsValidFolder 确保文件夹确实存在。
刷新资产数据库 :利用 AssetDatabase.Refresh() 确保 Unity 的资产数据库反映了文件系统的当前状态。
将这样的功能绑定到菜单项(如示例中的 MenuItem)允许你轻松地在编辑器中执行它,而不需要每次运行脚本。在使用脚本删除操作时,请确保在版本控制下操作,并注意备份关键数据,防止误删。
Not yet included in a published release.
using System;
using System.IO;
using System.Threading;
using System.Collections.Concurrent;
namespace DevKit
{
public class FileWriterLogger : ILog, IDisposable
{
private int _logLevel = Log.debugLevel;
private string _filePath;
private BlockingCollection<string> _logQueue = new BlockingCollection<string>();
private Thread _loggingThread;
private StreamWriter _streamWriter;
private bool _disposing = false;
public FileWriterLogger()
{
// Start the logging thread
_loggingThread = new Thread(ProcessLogQueue) { IsBackground = true };
_loggingThread.Start();
}
public void SetLogLevel(int logLevel)
{
_logLevel = logLevel;
}
public int GetLogLevel()
{
return _logLevel;
}
public void SetFilePath(string filePath)
{
_filePath = filePath;
EnsureLogFileExists();
}
private void EnsureLogFileExists()
{
if (string.IsNullOrEmpty(_filePath))
{
throw new InvalidOperationException("File path is not set.");
}
var fileInfo = new FileInfo(_filePath);
fileInfo.Directory?.Create(); // Create the directory if it doesn't exist
// Create the file stream and StreamWriter
_streamWriter = new StreamWriter(new FileStream(_filePath, FileMode.Append, FileAccess.Write, FileShare.Read))
{
AutoFlush = true
};
}
private void ProcessLogQueue()
{
foreach (var logMessage in _logQueue.GetConsumingEnumerable())
{
if (_streamWriter != null)
{
WriteLogToFile(logMessage);
}
}
}
private void WriteLogToFile(string message)
{
lock (_streamWriter) // Ensure that writing to the stream is thread-safe
{
_streamWriter.WriteLine(message);
}
}
public void Error(string message)
{
if (_logLevel >= Log.errorLevel)
{
_logQueue.Add("[ERROR] " + DateTime.Now + ": " + message);
}
}
public void Warning(string message)
{
if (_logLevel >= Log.warningLevel)
{
_logQueue.Add("[WARNING] " + DateTime.Now + ": " + message);
}
}
public void Info(string message)
{
if (_logLevel >= Log.infoLevel)
{
_logQueue.Add("[INFO] " + DateTime.Now + ": " + message);
}
}
public void Debug(string message)
{
if (_logLevel >= Log.debugLevel)
{
_logQueue.Add("[DEBUG] " + DateTime.Now + ": " + message);
}
}
public void Dispose()
{
if (!_disposing)
{
_disposing = true;
_logQueue.CompleteAdding(); // Signal completion
_loggingThread.Join(); // Wait for the logging thread to finish
lock (_streamWriter)
{
_streamWriter?.Close();
_streamWriter = null;
}
}
}
}
}
关键点
文件流和 StreamWriter : 使用 StreamWriter 和 FileStream 并设置 AutoFlush 为 true,确保每条日志都被及时写入磁盘。
线程安全 : 使用 lock 确保对 StreamWriter 的访问是线程安全的。
后台线程 : 日志处理在一个后台线程中进行,利用 BlockingCollection<string> 保证线程安全的队列操作。
Dispose 模式 : 在 Dispose 方法中正确关闭和释放 StreamWriter,并等待日志处理线程完成。
应用程序生命周期 : 确保应用程序退出时调用 Dispose,例如在 AppDomain.ProcessExit 或应用程序框架的生命周期事件中处理。
请根据你的应用程序需要具体调整这段代码,确保整个生命周期管理和异常处理符合你的需求。
如何使用
创建 Editor 脚本 :将上述代码放入一个脚本中,并将其保存到 Unity 项目的 Editor 文件夹中(例如 Assets/Editor/DebugLogChecker.cs)。
运行工具 :在 Unity 菜单栏中,选择 Tools > Debug.Log Checker 打开窗口。点击 Check for Debug.Log usages 按钮即可扫描项目中所有的 C# 脚本。
提示信息 :工具会在 Unity 的控制台输出 Debug.Log 的使用位置,并建议替换为 Log.Info。你可以双击控制台信息跳转到对应的代码行。
注意事项
正则表达式 :此示例中使用的正则表达式是基础匹配,它可以匹配绝大多数场景的直接使用。对于更复杂的场景(例如不同命名空间或条件编译的代码),可能需要调整或改进正则表达式。
文件修改工具 :可以进一步扩展此工具,让它直接替换 Debug.Log 为 Log.Info,不过需要处理版本控制(如 Git)以防止潜在的错误。
性能考虑 :对于大型项目,代码检查可能耗费一些时间,建议在项目不繁忙或离线时使用。
说明
结果存储 : 将所有包含 Debug.Log 使用的脚本路径存储在 resultFiles 列表中。
可视化列表 : 使用 GUILayout.BeginScrollView 和 GUILayout.Button 在编辑器窗口中显示每个包含 Debug.Log 的脚本路径。
文件选择 : 点击每个结果后,会自动在 Unity 编辑器中选中该 MonoScript 对象,从而便于开发者快速导航和修改。
这样,你可以在 Unity 编辑器中直接查看和处理所有包含 Debug.Log 调用的脚本文件。
} 完善上述代码, 1.查找时剔除_excludeDirs目录中的文件 2.查找结果中显示每个文件的resultContent
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace DevKit.Editor
{
public class DebugLogCheckerWindow : EditorWindow
{
private List<string> _resultFiles = new();
private Dictionary<string, StringBuilder> _resultContents = new();
private Vector2 _scrollPosition = Vector2.zero;
private static string[] _excludeDirs = new string[]
{
"Plugins",
"Editor"
};
[MenuItem("DevKit/Log/DebugLogChecker")]
public static void ShowWindow()
{
GetWindow(typeof(DebugLogCheckerWindow), false, "Debug Log Checker");
}
private void OnGUI()
{
if (GUILayout.Button("Check for Debug.Log usages"))
{
_resultFiles.Clear();
_resultContents.Clear();
_checkDebugLogUsages();
}
if (_resultFiles.Count > 0)
{
GUILayout.Label("Scripts with Debug.Log usage:");
_scrollPosition = GUILayout.BeginScrollView(_scrollPosition);
foreach (var file in _resultFiles)
{
if (GUILayout.Button(file))
{
// 选中并高亮在 Project 视图中的文件
var asset = AssetDatabase.LoadAssetAtPath<MonoScript>(file);
if (asset != null)
{
Selection.activeObject = asset;
}
}
// 显示详细结果内容
if (_resultContents.ContainsKey(file))
{
GUILayout.Label(_resultContents[file].ToString());
}
}
GUILayout.EndScrollView();
}
else
{
GUILayout.Label("No Debug.Log usages found.");
}
}
private void _checkDebugLogUsages()
{
string[] scriptPaths = Directory.GetFiles(Application.dataPath, "*.cs", SearchOption.AllDirectories);
foreach (string scriptPath in scriptPaths)
{
if (IsExcludedPath(scriptPath))
{
continue;
}
string scriptContent = File.ReadAllText(scriptPath);
// 通过正则表达式查找 Debug.Log 的使用
MatchCollection matches = Regex.Matches(scriptContent, @"\bDebug\.Log\w*\b");
if (matches.Count > 0)
{
string relativePath = "Assets" + scriptPath.Replace(Application.dataPath, "").Replace('\\', '/');
// 将找到的文件路径加入结果列表
_resultFiles.Add(relativePath);
Debug.LogWarning($"Found {matches.Count} usage(s) of Debug.Log in {relativePath}. Consider replacing with Log.Info.");
var resultContent = new StringBuilder();
_resultContents[relativePath] = resultContent;
foreach (Match match in matches)
{
int lineIndex = scriptContent.Substring(0, match.Index).Split('\n').Length;
var resultLine = $"Located at line: {lineIndex}";
resultContent.AppendLine(resultLine);
Debug.LogWarning(resultLine);
}
}
}
}
private bool IsExcludedPath(string scriptPath)
{
string normalizedPath = scriptPath.Replace('\\', '/');
foreach (var excludeDir in _excludeDirs)
{
if (normalizedPath.Contains($"/{excludeDir}/"))
{
return true;
}
}
return false;
}
}
}
代码说明
排除目录 :IsExcludedPath 方法检查给定路径是否在 _excludeDirs 中指定的目录。我们用 normalizedPath.Contains($"/{excludeDir}/") 来确认给定的路径是否含有这些要排除的目录部分。
显示详细结果内容 :在 OnGUI 方法中,GUILayout.Label(_resultContents[file].ToString()); 用于展示每个文件的详细结果内容,这些内容是通过 StringBuilder 累计的。
处理改进 :确保 _resultContents.Clear(); 被调用以保证在每次扫描时结果字典被清空,以免混入上次的结果。
private static string[] _excludeDirs = new string[]
{
"Plugins",
"Editor"
};
[MenuItem("DevKit/Log/DebugLogChecker")]
public static void ShowWindow()
{
GetWindow(typeof(DebugLogCheckerWindow), false, "Debug Log Checker");
}
private void OnGUI()
{
if (GUILayout.Button("Check for Debug.Log usages"))
{
_resultFiles.Clear();
_resultContents.Clear();
_checkDebugLogUsages();
}
if (_resultFiles.Count > 0)
{
GUILayout.Label("Scripts with Debug.Log usage:");
_scrollPosition = GUILayout.BeginScrollView(_scrollPosition);
foreach (var file in _resultFiles)
{
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button(file))
{
// 选中并高亮在 Project 视图中的文件
var asset = AssetDatabase.LoadAssetAtPath<MonoScript>(file);
if (asset != null)
{
Selection.activeObject = asset;
}
}
if (GUILayout.Button("ReplaceAll"))
{
var asset = AssetDatabase.LoadAssetAtPath<MonoScript>(file);
if (asset != null)
{
if (EditorUtility.DisplayDialog("ReplaceAll",
"Are you sure you want to replace all Debug.Log usages in this script?", "Yes",
"No"))
{
_replaceDebugLogUsages(asset.text);
}
}
}
EditorGUILayout.EndHorizontal();
// 显示详细结果内容
if (_resultContents.ContainsKey(file))
{
GUILayout.Label(_resultContents[file].ToString());
}
}
GUILayout.EndScrollView();
}
else
{
GUILayout.Label("No Debug.Log usages found.");
}
}
private void _checkDebugLogUsages()
{
string[] scriptPaths = Directory.GetFiles(Application.dataPath, "*.cs", SearchOption.AllDirectories);
foreach (string scriptPath in scriptPaths)
{
if (IsExcludedPath(scriptPath))
{
continue;
}
string scriptContent = File.ReadAllText(scriptPath);
// 通过正则表达式查找 Debug.Log 的使用
MatchCollection matches = Regex.Matches(scriptContent, @"\bDebug\.Log\w*\b");
if (matches.Count > 0)
{
string relativePath = "Assets" + scriptPath.Replace(Application.dataPath, "").Replace('\\', '/');
var lines = scriptContent.Split("\n");
// 将找到的文件路径加入结果列表
_resultFiles.Add(relativePath);
Debug.LogWarning($"Found {matches.Count} usage(s) of Debug.Log in {relativePath}. Consider replacing with Log.Info.");
var resultContent = new StringBuilder();
_resultContents[relativePath] = resultContent;
foreach (Match match in matches)
{
int lineIndex = scriptContent.Substring(0, match.Index).Split('\n').Length;
var resultLine = $"Located at line: {lineIndex}, {lines[lineIndex-1]}";
resultContent.AppendLine(resultLine);
Debug.LogWarning(resultLine);
}
}
}
}
private bool IsExcludedPath(string scriptPath)
{
string normalizedPath = scriptPath.Replace('\\', '/');
foreach (var excludeDir in _excludeDirs)
{
if (normalizedPath.Contains($"/{excludeDir}/"))
{
return true;
}
}
return false;
}
}
} 完善上述代码中_replaceDebugLogUsages的功能
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace DevKit.Editor
{
public class DebugLogCheckerWindow : EditorWindow
{
private List<string> _resultFiles = new();
private Dictionary<string, StringBuilder> _resultContents = new();
private Vector2 _scrollPosition = Vector2.zero;
private static string[] _excludeDirs = new string[]
{
"Plugins",
"Editor"
};
[MenuItem("DevKit/Log/DebugLogChecker")]
public static void ShowWindow()
{
GetWindow(typeof(DebugLogCheckerWindow), false, "Debug Log Checker");
}
private void OnGUI()
{
if (GUILayout.Button("Check for Debug.Log usages"))
{
_resultFiles.Clear();
_resultContents.Clear();
_checkDebugLogUsages();
}
if (_resultFiles.Count > 0)
{
GUILayout.Label("Scripts with Debug.Log usage:");
_scrollPosition = GUILayout.BeginScrollView(_scrollPosition);
foreach (var file in _resultFiles)
{
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button(file))
{
// 选中并高亮在 Project 视图中的文件
var asset = AssetDatabase.LoadAssetAtPath<MonoScript>(file);
if (asset != null)
{
Selection.activeObject = asset;
}
}
if (GUILayout.Button("ReplaceAll"))
{
var asset = AssetDatabase.LoadAssetAtPath<MonoScript>(file);
if (asset != null)
{
if (EditorUtility.DisplayDialog("ReplaceAll",
"Are you sure you want to replace all Debug.Log usages in this script?", "Yes",
"No"))
{
_replaceDebugLogUsages(asset.text, file);
}
}
}
EditorGUILayout.EndHorizontal();
// 显示详细结果内容
if (_resultContents.ContainsKey(file))
{
GUILayout.Label(_resultContents[file].ToString());
}
}
GUILayout.EndScrollView();
}
else
{
GUILayout.Label("No Debug.Log usages found.");
}
}
private void _checkDebugLogUsages()
{
string[] scriptPaths = Directory.GetFiles(Application.dataPath, "*.cs", SearchOption.AllDirectories);
foreach (string scriptPath in scriptPaths)
{
if (IsExcludedPath(scriptPath))
{
continue;
}
string scriptContent = File.ReadAllText(scriptPath);
// 通过正则表达式查找 Debug.Log 的使用
MatchCollection matches = Regex.Matches(scriptContent, @"\bDebug\.Log\w*\b");
if (matches.Count > 0)
{
string relativePath = "Assets" + scriptPath.Replace(Application.dataPath, "").Replace('\\', '/');
var lines = scriptContent.Split("\n");
// 将找到的文件路径加入结果列表
_resultFiles.Add(relativePath);
Debug.LogWarning($"Found {matches.Count} usage(s) of Debug.Log in {relativePath}. Consider replacing with Log.Info.");
var resultContent = new StringBuilder();
_resultContents[relativePath] = resultContent;
foreach (Match match in matches)
{
int lineIndex = scriptContent.Substring(0, match.Index).Split('\n').Length;
var resultLine = $"Located at line: {lineIndex}, {lines[lineIndex - 1]}";
resultContent.AppendLine(resultLine);
Debug.LogWarning(resultLine);
}
}
}
}
private void _replaceDebugLogUsages(string content, string filePath)
{
// 使用正则表达式替换 Debug.Log* 调用为 Log.Info 或其他定义的日志方法
string updatedContent = Regex.Replace(content, @"\bDebug\.Log\w*\b", "Log.Info");
// 将更新后的内容写回到文件中
File.WriteAllText(filePath, updatedContent);
// 刷新资产数据库以反映更改
AssetDatabase.Refresh();
Debug.Log($"Replaced Debug.Log usages in {filePath}.");
}
private bool IsExcludedPath(string scriptPath)
{
string normalizedPath = scriptPath.Replace('\\', '/');
foreach (var excludeDir in _excludeDirs)
{
if (normalizedPath.Contains($"/{excludeDir}/"))
{
return true;
}
}
return false;
}
}
}
代码说明
_replaceDebugLogUsages 方法 :
用 Regex.Replace(content, @"\bDebug\.Log\w*\b", "Log.Info") 将所有 Debug.Log 变量替换为 Log.Info。
使用 File.WriteAllText(filePath, updatedContent); 将更新后的脚本内容写回对应的文件。
刷新数据库 :
使用 AssetDatabase.Refresh(); 更新 Unity 的资产数据库,以确保编辑器立即反映更改。
用户提示 :
通过 Debug.Log 来确认哪一个文件被更新。
请确保在使用该功能之前备份你的代码,以防出现不期望的替换行为。
2. 使用步骤:
定义构建配置文件 :在 GetAllBuildProfilers 方法中,用列表初始化你的构建配置文件对象。在生产环境中,你可能需要动态加载或从脚本对象中检索这些配置。
下拉选择菜单 :通过 EditorGUILayout.Popup 创建下拉选择菜单。selectedProfilerIndex 用于跟踪当前选中的配置文件索引。
显示详细信息 :用 DisplayProfilerDetails 方法来显示选中配置文件的详细信息。这个方法根据你的实际 BuildProfiler 类的属性进行定制。
应用配置文件 :在 ApplyBuildProfiler 方法中定义如何应用选中的构建配置文件。
通过这种实现,你可以方便地在 Unity Editor 中选择和管理不同的构建配置文件。根据具体需求,可能需要调整 BuildProfiler 的结构和属性以适应你的项目。