Skip to main content
 首页 » 编程设计

c#之Assetbundle 不适用于 iOS

2024年02月05日19insus

我正在 Unity 中为 iPhone 开发一个 AR 应用程序,它从网络服务器下载 Assets 包并将它们附加到图像目标。到目前为止,几乎一切正常——除了当应用程序尝试加载 Assets 包时,我收到以下错误:

'asset/bundle/url' can't be loaded because it was not built with the right version or build target.

我使用以下脚本创建了 assetbundle,根据 Unity 文档稍作修改:

using UnityEditor; 
 
public class CreateAssetBundles 
{ 
    [MenuItem ("Assets/Build AssetBundles")] 
    static void BuildAllAssetBundles () 
    { 
        BuildPipeline.BuildAssetBundles ("Assets/AssetBundles", BuildAssetBundleOptions.None, BuildTarget.iOS); 
    } 
} 

然后我使用 scp 将 Assets 包上传到服务器。该应用程序可以很好地下载 Assets 包,但无法加载它们。这是代码:

IEnumerator DownloadAndCache (string username, string modelName){ 
        // Wait for the Caching system to be ready 
        while (!Caching.ready) { 
            Debug.Log ("Waiting on caching"); 
            yield return null; 
        } 
 
        //Compute request url for server 
        UriBuilder uriBuilder = new UriBuilder(); 
        uriBuilder.Scheme = "http"; 
        uriBuilder.Host = BaseURL; 
        uriBuilder.Path = username.Trim() + "/" + modelName.Trim(); 
        string BundleURL = uriBuilder.ToString (); 
        Debug.Log ("Attempting to download " + BundleURL); 
 
        // Load the AssetBundle file from Cache if it exists with the same version or download and store it in the cache 
        using(WWW www = WWW.LoadFromCacheOrDownload (BundleURL, version)){ 
            yield return www; 
            if (www.error != null) { 
                Debug.Log ("Download error"); 
                throw new Exception ("WWW download had an error:" + www.error); 
            } 
            AssetBundle bundle = www.assetBundle; 
            Debug.Log ("Got assets "+string.Join(",", bundle.GetAllAssetNames ())); 
            GameObject loadedModel = Instantiate(bundle.LoadAllAssets()[0]) as GameObject; 
 
            //attach to the image target 
            loadedModel.transform.parent = ImageTargetTemplate.gameObject.transform; 
            loadedModel.transform.position = new Vector3 (0, 0, 0); 
            loadedModel.transform.localScale = new Vector3 (1, 1, 1); 
 
            // Unload the AssetBundles compressed contents to conserve memory 
            bundle.Unload(false); 
 
        } // memory is freed from the web stream (www.Dispose() gets called implicitly) 
    } 

到目前为止我已经尝试过:

  • 设置构建目标 BuildTarget.iPhone - 没有区别
  • 使用 Unity 的 assetbundle 管理器 API 构建 assetbundle
  • 在 iOS 的构建选项中取消选中“剥离引擎代码”——我在另一个论坛上听说这会导致问题。

感谢任何帮助。

-更新-
我根据程序员的建议修改了 BuildAssetBundle 脚本,并在播放器设置面板中将目标平台从“iPhone”切换为“Universal”。我很确定这就是解决问题的原因。

请您参考如下方法:

这意味着当您构建 Assets 包时,您的目标设备不是 iOS。将目标更改为 iOS,然后重建 Asset Bundle。

重新编译并重新上传到 iOS,这应该可以解决您的问题。

如果那没有用,那么... 如果您在脚本后端设置为 IL2CPP 时构建了 AssetBundle,但随后将它们与 .NET 脚本后端一起使用,也会发生该错误。解决方案是在通过播放器设置更改为 .NET 脚本后端后重建您的 Asset Bundle。

同时尝试将 BuildTarget.iPhone 替换为 EditorUserBuildSettings.activeBuildTarget,这样 Bundle 将自动为当前选择的任何构建目标构建。