在Unity中构build和加载AssetBundles
我无法在iOS版本中使用Unity AssetBundles。
在Unity中,我构build了资产捆绑:
using UnityEditor; public class CreateAssetBundles { [MenuItem("Assets/Build AssetBundles")] static void BuildAllAssetBundles() { BuildPipeline.BuildAssetBundles("Assets/AssetBundles", BuildAssetBundleOptions.None, BuildTarget.iOS); } }
而且他们在Unity中工作得很好。 与他们一起使用
AssetBundle bundleLoadRequest = AssetBundle.LoadFromFile("file://" + Application.dataPath + "/AssetBundles/iOS/" + myassetbundlename.ToString());
和/或
WWW wwww = WWW.LoadFromCacheOrDownload("file://" + Application.dataPath + "/AssetBundles/iOS/" + myassetbundlename.ToString(), 4);
(如果没有“file://”前缀,捆绑包将不能在Unity和Xcode中使用)
我build立项目到Xcode并在Xcode中运行,并收到此错误:
无法打开档案文件:/ Users / user / Documents / Workspaces / unityproject / Assets / AssetBundles / iOS / lchairanimations
这可能是相关的设置正确的path,但因为我已经将assetsbundle文件夹复制到Xcode项目,问题依然存在。
在构buildAssetBundle时,您应该将它们放在StreamingAssets
文件夹中。 如果您尚未完成此操作,请在Assets
文件夹中创buildStreamingAssets
文件夹。 在里面,创build另一个名为AssetBundle
文件夹。 这只是为了组织StreamingAssets
文件夹中的内容。
最终的path应该是Assets/StreamingAssets/AssetBundle
。
加载时,应使用Application.streamingAssetsPath
访问StreamingAssets
文件夹。
要访问所有文件夹使用, Application.streamingAssetsPath + "/AssetBundle/" + assetbunlenameWithoutExtension;
build议使用Path.Combine
组合path名,以便下面的代码应该使用它。
你的构build脚本 :
public class ExportAssetBundles { [MenuItem("Assets/Build AssetBundle")] static void ExportResource() { string folderName = "AssetBundles"; string filePath = Path.Combine(Application.streamingAssetsPath, folderName); BuildPipeline.BuildAssetBundles(filePath, BuildAssetBundleOptions.None, BuildTarget.iOS); } }
您的加载脚本 :
IEnumerator loadAsset(string assetBundleName, string objectNameToLoad) { string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "AssetBundles"); filePath = System.IO.Path.Combine(filePath, assetBundleName); var assetBundleCreateRequest = AssetBundle.LoadFromFileAsync(filePath); yield return assetBundleCreateRequest; AssetBundle asseBundle = assetBundleCreateRequest.assetBundle; AssetBundleRequest asset = asseBundle.LoadAssetAsync<GameObject>(objectNameToLoad); yield return asset; GameObject loadedAsset = asset.asset as GameObject; //Do something with the loaded loadedAsset object }
用法 :
1。使用上面的第一个脚本( ExportAssetBundles
)通过转到Assets – > Build AssetBundle菜单来构build你的AssetBudle。
您应该在Assets/StreamingAssets/AssetBundles
目录中看到构build的AssetBundles。
2 。 我们来做下面的假设:
A。 Assetbundle的名字是animals
。
B。 我们要从动物中加载的对象的名称Assetbundle是dog
。
加载很简单,如下所示:
string nameOfAssetBundle = "animals"; string nameOfObjectToLoad = "dog"; StartCoroutine(loadAsset(nameOfAssetBundle, nameOfObjectToLoad));