内容将会持续更新,有错误的地方欢迎指正,谢谢!
拥有更好的学习体验 —— 不断努力,不断进步,不断探索 |
助力快速掌握 Project视图 编辑器扩展 为初学者节省宝贵的学习时间,避免困惑! |
文章目录
一、EditorApplication.projectChanged 之自动更新资源依赖报告
使用 EditorApplication.projectChanged 可以在项目资源发生变化时自动执行一些功能。下面展示如何使用这个事件在Unity项目中实现一个简单但实用的功能:自动更新资源依赖报告。
当项目资源变化时自动生成一份资源依赖报告,列出哪些资源被哪些其他资源依赖。这在进行资源优化或清理时非常有用。
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
[InitializeOnLoad]
public static class DependencyReportGenerator
{
private const string ReportPath = "Assets/DependencyReport.txt";
static DependencyReportGenerator()
{
EditorApplication.projectChanged += OnProjectChanged;
}
private static void OnProjectChanged()
{
Debug.Log("项目资源发生变化,正在生成依赖报告...");
Dictionary<string, List<string>> dependencyMap = GenerateDependencys();
GenerateReport(dependencyMap);
Debug.Log("依赖报告生成完毕。");
}
/// <summary>
/// 生成依赖项
/// </summary>
private static Dictionary<string, List<string>> GenerateDependencys()
{
string[] allAssetGuids = AssetDatabase.FindAssets("");
Dictionary<string, List<string>> dependencyMap = new Dictionary<string, List<string>>();
foreach (string guid in allAssetGuids)
{
string assetPath = AssetDatabase.GUIDToAssetPath(guid);
string[] dependencies = AssetDatabase.GetDependencies(assetPath, false);
foreach (string dependency in dependencies)
{
if (!dependencyMap.ContainsKey(dependency))
{
dependencyMap[dependency] = new List<string>();
}
dependencyMap[dependency].Add(assetPath);
}
}
return dependencyMap;
}
/// <summary>
/// 生成报告
/// </summary>
private static void GenerateReport(Dictionary<string, List<string>> dependencyMap)
{
using (StreamWriter writer = new StreamWriter(ReportPath))
{
foreach (var kvp in dependencyMap)
{
writer.WriteLine($"资源:{
kvp.Key}"