溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Unity中怎么獲取Shader 依賴

發(fā)布時間:2021-07-29 15:00:43 來源:億速云 閱讀:370 作者:Leah 欄目:大數(shù)據(jù)

Unity中怎么獲取Shader 依賴,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

介紹

Unity 中的 Shader 也會有依賴 Shader,例如通過 Dependency 或 Fallback 指令引用的 Shader,由于使用 AssetDatabase.GetDependencies API 無法獲得 Shader 的依賴,因此需要換一種方式實現(xiàn)。

思路

正確的做法是使用編譯器的思路解析整個 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);
           }
       }
   }
}

看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI