代码之家  ›  专栏  ›  技术社区  ›  WoShiNiBaBa

如何处理从网上下载文件后导入资产的问题?

  •  0
  • WoShiNiBaBa  · 技术社区  · 6 年前

    有没有办法避免这种情况,或者等到它完成后再加载文件?我正在为iOS开发

    下面是下载和加载.obj文件的代码:

    IEnumerator DownloadAndLoadFile(string url) { 
    
    var uwr = new UnityWebRequest(url, UnityWebRequest.kHttpVerbGET);
    string modelSavePath = Path.Combine(Application.dataPath, "Resources");
    modelSavePath = Path.Combine(modelSavePath, docName); 
    
        if (!Directory.Exists(Path.GetDirectoryName(modelSavePath)))
        {
            Directory.CreateDirectory(Path.GetDirectoryName(modelSavePath));
        }
    
     var dh = new DownloadHandlerFile(modelSavePath);
     dh.removeFileOnAbort = true; 
     uwr.downloadHandler = dh;  
    
    AsyncOperation request = uwr.SendWebRequest();
    while (!request.isDone)
        { 
            Debug.Log("Progress: " + request.progress);
            yield return null;
        }  
     if(request.isDone){
    
         Debug.Log("File successfully downloaded and saved to " + modelSavePath);
              // Load Main scene
            Scene s = SceneManager.GetSceneByName("Main");
            if (s.isLoaded) {
                             var allObjects = Resources.FindObjectsOfTypeAll<MainAssetSwitch>(); 
                                if (allObjects.Length > 0) { 
                                    var targetobject = allObjects [0];   
                                     targetobject.SetActive(true);
                                     Object prefabReference = Resources.Load(docName);
                                      GameObject gameObjectReference = Instantiate(prefabReference) as GameObject;
                                      ameObjectReference.transform.parent = targetobject.transform; 
                                } 
                }
    
    
     }
    
    if (uwr.isNetworkError || uwr.isHttpError)
        {Debug.LogError(uwr.error);}
    
    }
    

    下面是Unity在我加载从internet下载的.obj文件后将自动运行的内容。 enter image description here

    我还收到一个错误,说“ArgumentException:您要实例化的对象为null”,因为下载过程完成后,资产没有导入到资源文件中。 enter image description here

    1 回复  |  直到 6 年前
        1
  •  0
  •   Viktor Vasyliev    6 年前

    没有可导入的内置技术 .obj .fbx 在unity中创建模型并将其添加到运行时的场景中。

    AssetBundles 或者在资产库中找到一些用于此目的的资产。

    AssetBundle是包含特定于平台的资产的归档文件 (模型、纹理、预制、音频剪辑,甚至整个场景)可以在运行时加载。

    看看这些文件:

    https://docs.unity3d.com/Manual/AssetBundlesIntro.html https://docs.unity3d.com/Manual/AssetBundles-Building.html https://docs.unity3d.com/Manual/LoadingResourcesatRuntime.html https://docs.unity3d.com/Manual/UnityWebRequest-DownloadingAssetBundle.html