Unity 获取一个资源被那些资源引用

Unity 获取一个资源被那些资源引用

在 API 只知道了一个资源依赖其他资源的方法 AssetDatabase.GetDependencies
当删除一个资源时往往害怕它被其他资源引用,导致错误,往往需要找到具体哪些文件引用了该资源,Unity 没有提供方法,可以通过 AssetDatabase.GetDependencies 收集项目中所有资源的引用关系,比如项目中资源
A 引用了 D, B 引用了 C,
则 反向查找可以确定 D 被 A 引用了, C 被 B 引用了

在 Editor文件夹中新建脚本 AssetBeDepend.cs

using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class AssetBeDepend
{
    // 存储所有依赖关系
    private static Dictionary<string, List<string>> referenceCacheDic = new Dictionary<string, List<string>>();

    // 在 Assets 文件件下鼠标右键弹板中添加按钮 AssetBeDepend
    [MenuItem("Assets/AssetBeDepend")]
    static void Select()
    {
        CollectDepend();

        // 获取所有选中 文件、文件夹的 GUID
        string[] guids = Selection.assetGUIDs;
        foreach (var guid in guids)
        {
            // 将 GUID 转换为 路径
            string assetPath = AssetDatabase.GUIDToAssetPath(guid);
            IsBeDepend(assetPath);
        }
    }

    // 收集项目中所有依赖关系
    static void CollectDepend()
    {
        int count = 0;
        // 获取 Assets 文件夹下所有资源
        string[] guids = AssetDatabase.FindAssets("");
        foreach (string guid in guids)
        {
            // 将 GUID 转换为路径
            string assetPath = AssetDatabase.GUIDToAssetPath(guid);
            // 获取文件所有直接依赖的资源
            string[] dependencies = AssetDatabase.GetDependencies(assetPath, false);

            foreach (var filePath in dependencies)
            {
                // dependency 被 assetPath 依赖了
                // 将所有依赖关系存储到字典中
                List<string> list = null;
                if (!referenceCacheDic.TryGetValue(filePath, out list))
                {
                    list = new List<string>();
                    referenceCacheDic[filePath] = list;
                }
                list.Add(assetPath);
            }

            count++;
            EditorUtility.DisplayProgressBar("Search Dependencies", "Dependencies", (float)(count * 1.0f / guids.Length));
        }

        EditorUtility.ClearProgressBar();
    }

    // 判断文件是否被依赖
    static bool IsBeDepend(string filePath)
    {
        List<string> list = null;
        if (!referenceCacheDic.TryGetValue(filePath, out list))
        {
            return false;
        }

        // 将依赖关系打印出来
        foreach(var file in list)
        {
            Debug.LogError(filePath + "   被:" + file + "    引用");
        }

        return true;
    }

}

代码中注释比较详细了,不在详解代码

测试方法:在 Assets 文件夹下选中一个、多个文件,鼠标右键,在弹出面板中点击 AssetBeDepend 按钮

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值