在Unity工程苏潜,所有的資源存放在Assets目錄下银萍,包括腳步、貼圖恤左、模型贴唇、材質(zhì)、Prefab等等飞袋。
Prefab是Unity提供一個(gè)以yaml表示的資源序列化文件戳气。通常我們通過(guò)Prefab去整合其他資源來(lái)使用。
Unity通過(guò)Prefab去存儲(chǔ)一個(gè)GameObject巧鸭,GameObject上有多個(gè)Compoent以及一些其他屬性瓶您。
Unity會(huì)幫助我們自動(dòng)化的管理被Prefab依賴到的所有資源的引用,自動(dòng)加載卸載纲仍。
Assets目錄
在Assets目錄下的資源都可以通過(guò)一個(gè)Editor接口去加載呀袱。
AssetDatabase.LoadAssetAtPath<T>(assetPath)可以加載到這個(gè)路徑下的資源。
注意這里的assetPath是從Assets目錄開(kāi)始的一個(gè)全路徑郑叠,并且?guī)U(kuò)展名压鉴。
AssetDatabase.LoadAssetAtPath<GameObject>("Assets/Resources/Model/Cube.prefab");
但在打包的時(shí)候只有特定目錄的資源才會(huì)被打進(jìn)包。
Resources目錄
Resources目錄下的資源锻拘,以及被該目錄下資源引用到的資源都會(huì)被打到包里面去油吭。
我們可以通過(guò)Resources.Load<T>(path)加載資源。
注意這里的path是相對(duì)于Resources目錄的相對(duì)路徑署拟,并且沒(méi)有擴(kuò)展名婉宰。
// assetPath = "Assets/Resources/Model/Cube.prefab"
Resources.Load<GameObject>("Model/Cube");
StreamingAssets目錄
StreamingAssets目錄下的資源也會(huì)被打倒包里面去,不過(guò)Unity不會(huì)對(duì)這目錄下的資源做任何處理推穷。
通常這個(gè)目錄存放文本心包、音頻、視頻馒铃、以及AssetBundle蟹腾。
通過(guò)WWW和AssetBundle我們都可以加載在這個(gè)目錄的AssetBundle資源
注意Android的加載路徑需要使用 Application.dataPath+”!assets”來(lái)加載
SteamingAssetsPath官方文檔
// 通過(guò)www加載
string url = System.IO.Path.Combine(Application.streamingAssetsPath, "Cube.assetbundle");
WWW www = new WWW(url);
yield return www;
AssetBundle assetBundle = www.assetBundle as AssetBundle;
// Android平臺(tái) AssetBundle加載
string path = string.Format("{0}!assets/Cube.assetbundle", Application.dataPath);
AssetBundle assetBundle2 = AssetBundle.LoadFromFile(path);
// 其他平臺(tái) AssetBundle加載
string path2 = System.IO.Path.Combine(Application.streamingAssetsPath, "Cube.assetbundle");
AssetBundle assetBundle3 = AssetBundle.LoadFromFile(path2);
總結(jié)
資源管理一直是性能問(wèn)題的核心痕惋,了解Unity對(duì)資源加載的設(shè)計(jì),設(shè)計(jì)自己的資源管理器娃殖。
同時(shí)針對(duì)不同平臺(tái)值戳,不同機(jī)型定制對(duì)應(yīng)的資源管理策略。