简体   繁体   中英

Unity3d Loading assetbundle

I'm experimenting with Unity3d AssetBundles. I'm trying to load a scene with its objects. I have this simple code for creating my asset bundle :

 [MenuItem ("Build/BuildAssetBundle")]
 static void myBuild(){
     string[] levels = {"Assets/main.unity"};
     BuildPipeline.BuildStreamedSceneAssetBundle(levels,"Streamed-Level1.unity3d",BuildTarget.Android);
 }

and I use above code to build asset bundle from a scene which in has a camera and a cube in center.

and I have this code to load it:

 using UnityEngine;
 using System.Collections;

 public class loader : MonoBehaviour {

     public GUIText debugger;
     private string url = "http://www.myurl.com/Streamed-Level1.unity3d";
     // Use this for initialization
     IEnumerator Start () {
         Debug.Log("starting");
         WWW www = WWW.LoadFromCacheOrDownload(url,1);
         if(www.error != null)
         {
             Debug.LogError(www.error);
         }
         yield return www;
         Debug.Log("after yield");
         AssetBundle bundle = www.assetBundle;
         bundle.LoadAll();
         Debug.Log("loaded all");
         Application.LoadLevel("main");


     }

     // Update is called once per frame
     void Update () {

     }
 }

The problem is seems to be when it gets to get to loadAll it stops.

I'll appreciate if anyone can help me with this.

Thanks very much

The problem is C# have iterators/generators and so on that looks like a function but they don't. So your code just create iterator but do not run it. Use StartCoroutine to load asset:

using UnityEngine;
using System.Collections;

public class BundleLoader : MonoBehaviour{
    public string url;
    public int version;
    public IEnumerator LoadBundle(){
        using(WWW www = WWW.LoadFromCacheOrDownload(url, version){
            yield return www;
            AssetBundle assetBundle = www.assetBundle;
            GameObject gameObject = assetBundle.mainAsset as GameObject;
            Instantiate(gameObject );
            assetBundle.Unload(false);
        }
    }
    void Start(){
        StartCoroutine(LoadBundle());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM