Unity---資源管理中不同資源的路徑獲取方式
阿新 • • 發佈:2018-11-09
1、首先需要先了解兩個知識點: Unity內建的檔案路徑獲取方式、windows的Directory.GetFiles檔案獲取方式:
1>Unity內建的檔案路徑獲取方式,一下是官方解釋:https://docs.unity3d.com/ScriptReference/AssetDatabase.FindAssets.html
以下是自己對AssetDatabase類中一些方法的簡單測試:
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine;4 using UnityEditor; 5 6 using UnityEngine; 7 using UnityEditor; 8 9 public class TestAssetDatabase : Editor 10 { 11 const string TestMatPath = @"Assets/Materials/"; 12 const string TestMatName = "TestMaterial.mat"; 13 14 static string MatPath = string.Format("{0}{1}", TestMatPath, TestMatName);15 16 [MenuItem("Tools/Create Asset")] 17 static void CreateMaterial() 18 { 19 var material = new Material(Shader.Find("Specular")); 20 AssetDatabase.CreateAsset(material, MatPath); //Materials資料夾 需要手動建立 21 } 22 23 [MenuItem("Tools/Delete Asset")] 24 static voidDeleteMaterial() 25 { 26 AssetDatabase.DeleteAsset(MatPath); 27 } 28 29 [MenuItem("Tools/Copy Asset")] 30 static void CopyMaterial() 31 { 32 AssetDatabase.CopyAsset(MatPath, "Assets/NewMaterials/TestMaterial.mat"); //NewMaterials資料夾 需要手動建立 33 } 34 35 [MenuItem("Tools/Load Asset")] 36 static void LoadMaterial() 37 { 38 //載入資源兩種不同的寫法,需要些資源字尾的 39 //Material mat = AssetDatabase.LoadAssetAtPath<Material>(MatPath); 40 Material mat = AssetDatabase.LoadAssetAtPath(MatPath, typeof(Material)) as Material; 41 Debug.Log(mat.color); 42 } 43 44 45 //Filter可以是:Name、Lable、Type(內建的、自定義) 46 47 //Type 關鍵字 t: 48 static string fliterMat = "t:Material"; //單個 49 static string filterPrefab = "t:Prefab"; 50 static string fliterMatPre = "t:Material t:Prefab"; //多個 51 static string filterCustomDefine = "t:CustomDefine"; //自定義的型別,需要是ScriptableObject建立的資源 52 53 //Label 關鍵字 l: 54 static string filterLabel = "l:lgs"; 55 56 static string filterMixed = "Cube l:lgs"; //混合過濾---名字中有Cube,Label為 lgs 57 58 [MenuItem("Tools/Find Asset")] 59 static void FindAsset() 60 { 61 string[] guidArray = AssetDatabase.FindAssets(filterMixed); 62 foreach (string item in guidArray) 63 { 64 Debug.Log(AssetDatabase.GUIDToAssetPath(item)); //轉換來的資源路徑是帶有後綴名字的 65 } 66 } 67 }
2>windows的Directory.GetFiles檔案獲取方式,官方解釋:https://docs.microsoft.com/zh-cn/dotnet/api/system.io.directory.getfiles?view=netframework-4.7.2#System_IO_Directory_GetFiles_System_String_System_String_System_IO_SearchOption_
以下是官方程式碼示例(指定以字母開頭的檔案數):
1 using System; 2 using System.IO; 3 4 class Test 5 { 6 public static void Main() 7 { 8 try 9 { 10 // Only get files that begin with the letter "c." 11 string[] dirs = Directory.GetFiles(@"c:\", "c*"); 12 Console.WriteLine("The number of files starting with c is {0}.", dirs.Length); 13 foreach (string dir in dirs) 14 { 15 Console.WriteLine(dir); 16 } 17 } 18 catch (Exception e) 19 { 20 Console.WriteLine("The process failed: {0}", e.ToString()); 21 } 22 } 23 }
在獲取不同資源的時候,只需要對不同型別的資源加以不同的過濾標籤,
例如:
過濾器,若以t:開頭,表示用unity的方式過濾;若以f:開頭,表示用windows的SearchPattern方式過濾;若以r:開頭,表示用正則表示式的方式過濾
再根據過濾標籤,獲取不同的資源路徑即可