首页 > 解决方案 > 将assetBundle转换为游戏对象

问题描述

我已经从服务器加载了 Unity 中的模型,它在编辑器上运行良好,因为一切运行良好。但是当我在 Andriod 上运行它时,它并没有从这条线上继续前进

GameObject temp = (GameObject)bundle.LoadAsset(assetName);

我尝试了不同的方法来做到这一点,但结果是一样的,因为它在编辑器上运行良好,但在安卓上却不行

public IEnumerator DownloadAsset(WWW www, string assetName)
{
    yield return www;
    AssetBundle bundle = www.assetBundle;
    if (www.error == null)
    {
        GameObject temp = (GameObject)bundle.LoadAsset(assetName); 

        Instantiate(temp);
    }
}

标签: c#unity3d

解决方案


这很可能是由于尝试将加载的对象从 Asset Bundle 转换为 GameObject 时出现的异常。
(这主要发生在加载的对象不应该是游戏对象时)

您可以尝试使用as关键字进行转换。

// Tries to convert to GameObject, returns null if it fails
GameObject temp = _bundle.LoadAsset(_assetName) as GameObject;

if (temp != null){
    Instantiate(temp);
} else {
    // Failed to convert to gameObject
}

编辑

就像 derHugo 提到的那样,您应该改用UnityWebRequest
(您所做的是使用WWW,它不会在下载数据时将数据“转换”为 AssetBundle。)

按照在线网站,您应该得到以下结果:

   UnityWebRequest www = UnityWebRequest.GetAssetBundle("website Name to get the asset bundle");
   yield return www.SendWebRequest();

    if(www.isNetworkError || www.isHttpError) {
        // Error fetching the asset bundle from the website.
    }
    else {
        AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(www);
        GameObject temp = bundle.LoadAsset(assetName) as GameObject;

        if (temp != null){
            Instantiate(temp);
        } else {
            // Failed to convert to gameObject
        }
    }

推荐阅读