Unity中怎么获取Shader 依赖

发布时间:2021-07-29 15:00:43 作者:Leah
来源:亿速云 阅读:352

Unity中怎么获取Shader 依赖,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

介绍

Unity 中的 Shader 也会有依赖 Shader,例如通过 Dependency 或 Fallback 指令引用的 Shader,由于使用 AssetDatabase.GetDependencies API 无法获得 Shader 的依赖,因此需要换一种方式实现。

思路

正确的做法是使用编译器的思路解析整个 Shader,找到对应的依赖指令并解析出其中的 Shader 名字。但是这个方法实在是太重了。

简单的做法是使用正则表达式查找依赖指令,缺点是可能无法识别注释、多行注释之类的,不过实际使用还好。

代码

private static string[] GetDependencies(string assetPath)
{
   if (assetPath.EndsWith(".shader"))
   {
       var result = new List<string>();
       GetShaderDependencies(assetPath, result);
       return result.ToArray();
   }

   return AssetDatabase.GetDependencies(assetPath);
}

private static readonly string[] ShaderDepedencyPatterns =
{
   // Dependency "Tree0"         = "Hidden/TerrainEngine/BillboardTree"
   @"Dependency\s+"".*\""\s+=\s+""(.*)""",
   // Fallback "Diffuse"
   @"Fallback\s+""(.*)""",
};

private static void GetShaderDependencies(string assetPath, List<string> result, bool recursive = true)
{
   var text = File.ReadAllText(assetPath);
   for (int i = 0; i < ShaderDepedencyPatterns.Length; i++)
   {
       var matches = Regex.Matches(text, ShaderDepedencyPatterns[i], RegexOptions.Multiline);
       for (int j = 0; j < matches.Count; j++)
       {
           if (!matches[j].Success)
           {
               continue;
           }

           string shaderName = matches[j].Groups[1].Value;
           if (result.Contains(shaderName))
           {
               continue;
           }

           var shader = Shader.Find(shaderName);
           if (shader == null)
           {
               continue;
           }

           string shaderPath = AssetDatabase.GetAssetPath(shader);
           result.Add(shaderPath);
           if (recursive)
           {
               GetShaderDependencies(shaderPath, result, true);
           }
       }
   }
}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. unity 打包AssetBundle
  2. unity 在代码中创建spine动画组件

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

unity shader

上一篇:python中怎么利用appium获取app元素属性值

下一篇:MATLAB中怎么调用Python代码

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》