Unity 编辑器开发实战【AssetDatabase】- 获取资产的依赖项、引用项

简介: Unity 编辑器开发实战【AssetDatabase】- 获取资产的依赖项、引用项

image.gif

Unity AssetDatabase类中提供了获取资产依赖项的API,如果我们想要获取某一资产被哪些资产引用,可以通过如下思路去实现:

1.获取工程中的所有资产;

2.遍历每一项资产,获取其依赖项列表;

3.如果资产A的依赖项列表中包含资产B,则资产B被资产A引用。

用到的核心API:

1.根据guid获取资产路径

//// 摘要://     Gets the corresponding asset path for the supplied GUID, or an empty string if//     the GUID can't be found.//// 参数://   guid://     The GUID of an asset.//// 返回结果://     Path of the asset relative to the project folder.publicstaticstringGUIDToAssetPath(stringguid)
{
returnGUIDToAssetPath_Internal(newGUID(guid));
}

image.gif

2.根据资产路径获取资产的类型

//// 摘要://     Returns the type of the main asset object at assetPath.//// 参数://   assetPath://     Filesystem path of the asset to load.[MethodImpl(MethodImplOptions.InternalCall)]
publicstaticexternTypeGetMainAssetTypeAtPath(stringassetPath);

image.gif

3.根据资产路径获取该资产的依赖项:

//// 摘要://     Returns an array of all the assets that are dependencies of the asset at the//     specified pathName. Note: GetDependencies() gets the Assets that are referenced//     by other Assets. For example, a Scene could contain many GameObjects with a Material//     attached to them. In this case, GetDependencies() will return the path to the//     Material Assets, but not the GameObjects as those are not Assets on your disk.//// 参数://   pathName://     The path to the asset for which dependencies are required.////   recursive://     Controls whether this method recursively checks and returns all dependencies//     including indirect dependencies (when set to true), or whether it only returns//     direct dependencies (when set to false).//// 返回结果://     The paths of all assets that the input depends on.publicstaticstring[] GetDependencies(stringpathName)
{
returnGetDependencies(pathName, recursive: true);
}

image.gif

4.根据资产路径及类型加载资产

//// 摘要://     Returns the first asset object of type type at given path assetPath.//// 参数://   assetPath://     Path of the asset to load.////   type://     Data type of the asset.//// 返回结果://     The asset matching the parameters.[MethodImpl(MethodImplOptions.InternalCall)]
[NativeThrows]
[PreventExecutionInState(AssetDatabasePreventExecution.kGatheringDependenciesFromSourceFile, PreventExecutionSeverity.PreventExecution_ManagedException, "Assets may not be loaded while dependencies are being gathered, as these assets may not have been imported yet.")]
[TypeInferenceRule(TypeInferenceRules.TypeReferencedBySecondArgument)]
publicstaticexternUnityEngine.ObjectLoadAssetAtPath(stringassetPath, Typetype);

image.gif

下面实现的工具,既可以获取资产的依赖项,也可以获取资产的引用项:

image.gif

代码如下:

usingSystem;
usingUnityEngine;
usingUnityEditor;
usingSystem.Linq;
usingSystem.Collections.Generic;
namespaceSK.Framework{
publicclassAssetsStatistics : EditorWindow    {
        [MenuItem("SKFramework/Assets Statistics")]
privatestaticvoidOpen()
        {
GetWindow<AssetsStatistics>("Assets Statistics").Show();
        }
privateVector2selectedListScroll;
//当前选中项索引privateintcurrentSelectedIndex=-1;
privateenumMode        {
Dependence,
Reference,
        }
privateModemode=Mode.Dependence;
privateVector2dependenceListScroll;
privateVector2referenceListScroll;
privatestring[] dependenciesArray;
privatestring[] referenceArray;
privatevoidOnGUI()
        {
OnListGUI();
OnMenuGUI();
        }
privatevoidOnListGUI()
        {
if (Selection.assetGUIDs.Length==0) return;
selectedListScroll=EditorGUILayout.BeginScrollView(selectedListScroll);
for (inti=0; i<Selection.assetGUIDs.Length; i++)
            {
//通过guid获取资产路径stringpath=AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[i]);
GUILayout.BeginHorizontal(currentSelectedIndex==i?"SelectionRect" : "dragtab first");
//获取资产类型Typetype=AssetDatabase.GetMainAssetTypeAtPath(path);
GUILayout.Label(EditorGUIUtility.IconContent(GetIconName(type.Name)), GUILayout.Width(20f), GUILayout.Height(15f));
GUILayout.Label(path);
//点击选中if(Event.current.type==EventType.MouseDown&&GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition))
                {
currentSelectedIndex=i;
Event.current.Use();
GetDependencies();
                }
GUILayout.EndHorizontal();
            }
EditorGUILayout.EndScrollView();
        }
privatevoidOnMenuGUI()
        {
GUILayout.FlexibleSpace();
GUILayout.BeginVertical("Box", GUILayout.Height(position.height* .7f));
            {
GUILayout.BeginHorizontal();
                {
Colorcolor=GUI.color;
GUI.color=mode==Mode.Dependence?color : Color.gray;
if (GUILayout.Button("依赖", "ButtonLeft"))
                    {
mode=Mode.Dependence;
                    }
GUI.color=mode==Mode.Reference?color : Color.gray;
if (GUILayout.Button("引用", "ButtonRight"))
                    {
mode=Mode.Reference;
                    }
GUI.color=color;
                }
GUILayout.EndHorizontal();
switch (mode)
                {
caseMode.Dependence: OnDependenceGUI(); break;
caseMode.Reference: OnReferenceGUI(); break;
                }
            }
GUILayout.EndVertical();
        }
privatevoidGetDependencies()
        {
stringguid=Selection.assetGUIDs[currentSelectedIndex];
stringpath=AssetDatabase.GUIDToAssetPath(guid);
dependenciesArray=AssetDatabase.GetDependencies(path);
        }
privatevoidOnDependenceGUI()
        {
EditorGUILayout.HelpBox("该资产的依赖项", MessageType.Info);
if (currentSelectedIndex!=-1)
            {
dependenceListScroll=EditorGUILayout.BeginScrollView(dependenceListScroll);
for (inti=0; i<dependenciesArray.Length; i++)
                {
stringdependency=dependenciesArray[i];
GUILayout.BeginHorizontal("dragtab first");
Typetype=AssetDatabase.GetMainAssetTypeAtPath(dependency);
GUILayout.Label(EditorGUIUtility.IconContent(GetIconName(type.Name)), GUILayout.Width(20f), GUILayout.Height(15f));
GUILayout.Label(dependency);
if (Event.current.type==EventType.MouseDown&&GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition))
                    {
varobj=AssetDatabase.LoadAssetAtPath(dependency, type);
EditorGUIUtility.PingObject(obj);
Event.current.Use();
                    }
GUILayout.EndHorizontal();
                }
EditorGUILayout.EndScrollView();
            }
        }
privatevoidOnReferenceGUI()
        {
EditorGUILayout.HelpBox("该资产的引用项(需点击刷新按钮获取,需要一定时间)", MessageType.Info);
GUI.enabled=currentSelectedIndex!=-1;
if (GUILayout.Button("刷新")) 
            {
if (EditorUtility.DisplayDialog("提醒", "获取工程资产之间的引用关系需要一定时间,是否确定开始", "确定", "取消"))
                {
Dictionary<string, string[]>referenceDic=newDictionary<string, string[]>();
string[] paths=AssetDatabase.GetAllAssetPaths();
for (inti=0; i<paths.Length; i++)
                    {
referenceDic.Add(paths[i], AssetDatabase.GetDependencies(paths[i]));
EditorUtility.DisplayProgressBar("进度", "获取工程资产之间的依赖关系", i+1/paths.Length);
                    }
EditorUtility.ClearProgressBar();
stringguid=Selection.assetGUIDs[currentSelectedIndex];
stringpath=AssetDatabase.GUIDToAssetPath(guid);
referenceArray=referenceDic.Where(m=>m.Value.Contains(path)).Select(m=>m.Key).ToArray();
                }
            }
GUI.enabled=true;
if(referenceArray!=null)
            {
referenceListScroll=EditorGUILayout.BeginScrollView(referenceListScroll);
                {
for (inti=0; i<referenceArray.Length; i++)
                    {
stringreference=referenceArray[i];
GUILayout.BeginHorizontal("dragtab first");
Typetype=AssetDatabase.GetMainAssetTypeAtPath(reference);
GUILayout.Label(EditorGUIUtility.IconContent(GetIconName(type.Name)), GUILayout.Width(20f), GUILayout.Height(15f));
GUILayout.Label(reference);
if (Event.current.type==EventType.MouseDown&&GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition))
                        {
varobj=AssetDatabase.LoadAssetAtPath(reference, type);
EditorGUIUtility.PingObject(obj);
Event.current.Use();
                        }
GUILayout.EndHorizontal();
                    }
                }
EditorGUILayout.EndScrollView();
            }
        }
privatestringGetIconName(stringtypeName)
        {
switch (typeName)
            {
case"Material": return"d_Material Icon";
case"Mesh": return"d_Mesh Icon";
case"AnimationClip": return"d_AnimationClip Icon";
case"GameObject": return"d_Prefab Icon";
case"Texture2D": return"d_Texture Icon";
case"MonoScript": return"d_cs Script Icon";
case"AnimatorController": return"d_AnimatorController Icon";
case"DefaultAsset": return"d_DefaultAsset Icon";
case"TextAsset": return"d_TextAsset Icon";
case"TimelineAsset": return"d_UnityEditor.Timeline.TimelineWindow";
default: return"d__Help@2x";
            }
        }
privatevoidOnSelectionChange()
        {
currentSelectedIndex=-1;
Repaint();
        }
    }
}

image.gif

目录
相关文章
|
人机交互 开发工具 vr&ar
使用Unity引擎开发Rokid主机应用的模型交互操作
本文介绍如何使用Unity引擎结合Rokid OpenXR Plugin开发空间计算应用,实现射线交互、模型操作等功能。涵盖环境配置、Demo导入、UI搭建与脚本编写,助力开发者快速构建AR交互应用。
|
C# 图形学 开发者
Unity开发中使用UnityWebRequest从HTTP服务器下载资源。
总之,UnityWebRequest就是游戏开发者手中的万能钓鱼竿,既可以获取文本数据,也能钓上图片资源,甚至是那声音的涟漪。使用UnityWebRequest的时候,你需要精心准备,比如确定URL、配置请求类型和头信息;发起请求;巧妙处理钓获的数据;还需要机智面对网络波澜,处理各种可能出现的错误。按照这样的过程,数据的钓取将会是一次既轻松愉快也效率高效的编程钓鱼之旅。
962 18
|
小程序 PHP 图形学
热门小游戏源码(Python+PHP)下载-微信小程序游戏源码Unity发实战指南​
本文详解如何结合Python、PHP与Unity开发并部署小游戏至微信小程序。涵盖技术选型、Pygame实战、PHP后端对接、Unity转换适配及性能优化,提供从原型到发布的完整指南,助力开发者快速上手并发布游戏。
|
开发工具 Android开发 开发者
用Flet打造跨平台文本编辑器:从零到一的Python实战指南
本文介绍如何使用Flet框架开发一个跨平台、自动保存的文本编辑器,代码不足200行,兼具现代化UI与高效开发体验。
1646 0
|
前端开发
业余时间开发了个海报编辑器
为了满足撰写博客或录制教程视频时对高质量海报的需求,我利用业余时间开发了一款海报编辑器。第一版功能简单,支持固定尺寸、黑底白字的标题。后来经过优化,增加了背景图、模糊效果、文字样式调整等功能,使海报更具吸引力。目前该编辑器已上线,欢迎大家试用并反馈。[访问海报编辑器](https://tool.share888.top/#/poster)
481 6
业余时间开发了个海报编辑器
|
运维 Java Linux
【运维基础知识】掌握VI编辑器:提升你的Java开发效率
本文详细介绍了VI编辑器的常用命令,包括模式切换、文本编辑、搜索替换及退出操作,帮助Java开发者提高在Linux环境下的编码效率。掌握这些命令,将使你在开发过程中更加得心应手。
349 2
|
图形学 开发者 搜索推荐
Unity Asset Store资源大解密:自制与现成素材的优劣对比分析,教你如何巧用海量资产加速游戏开发进度
【8月更文挑战第31天】游戏开发充满挑战,尤其对独立开发者或小团队而言。Unity Asset Store 提供了丰富的资源库,涵盖美术、模板、音频和脚本等,能显著加快开发进度。自制资源虽具个性化,但耗时长且需专业技能;而 Asset Store 的资源经官方审核,质量可靠,可大幅缩短开发周期,使开发者更专注于核心玩法。然而,使用第三方资源需注意版权问题,且可能需调整以适应特定需求。总体而言,合理利用 Asset Store 能显著提升开发效率和项目质量。
842 1
|
开发者 图形学 API
从零起步,深度揭秘:运用Unity引擎及网络编程技术,一步步搭建属于你的实时多人在线对战游戏平台——详尽指南与实战代码解析,带你轻松掌握网络化游戏开发的核心要领与最佳实践路径
【8月更文挑战第31天】构建实时多人对战平台是技术与创意的结合。本文使用成熟的Unity游戏开发引擎,从零开始指导读者搭建简单的实时对战平台。内容涵盖网络架构设计、Unity网络API应用及客户端与服务器通信。首先,创建新项目并选择适合多人游戏的模板,使用推荐的网络传输层。接着,定义基本玩法,如2D多人射击游戏,创建角色预制件并添加Rigidbody2D组件。然后,引入网络身份组件以同步对象状态。通过示例代码展示玩家控制逻辑,包括移动和发射子弹功能。最后,设置服务器端逻辑,处理客户端连接和断开。本文帮助读者掌握构建Unity多人对战平台的核心知识,为进一步开发打下基础。
1387 0
|
开发者 图形学 Java
揭秘Unity物理引擎核心技术:从刚体动力学到关节连接,全方位教你如何在虚拟世界中重现真实物理现象——含实战代码示例与详细解析
【8月更文挑战第31天】Unity物理引擎对于游戏开发至关重要,它能够模拟真实的物理效果,如刚体运动、碰撞检测及关节连接等。通过Rigidbody和Collider组件,开发者可以轻松实现物体间的互动与碰撞。本文通过具体代码示例介绍了如何使用Unity物理引擎实现物体运动、施加力、使用关节连接以及模拟弹簧效果等功能,帮助开发者提升游戏的真实感与沉浸感。
1251 1
|
图形学 C++ C#
Unity插件开发全攻略:从零起步教你用C++扩展游戏功能,解锁Unity新玩法的详细步骤与实战技巧大公开
【8月更文挑战第31天】Unity 是一款功能强大的游戏开发引擎,支持多平台发布并拥有丰富的插件生态系统。本文介绍 Unity 插件开发基础,帮助读者从零开始编写自定义插件以扩展其功能。插件通常用 C++ 编写,通过 Mono C# 运行时调用,需在不同平台上编译。文中详细讲解了开发环境搭建、简单插件编写及在 Unity 中调用的方法,包括创建 C# 封装脚本和处理跨平台问题,助力开发者提升游戏开发效率。
2116 0