Unity3D How to using AssetBundle.LoadAsync direct load prefab from Assets folder

user2982999 picture user2982999 · Nov 12, 2013 · Viewed 9.4k times · Source

Can i using AssetBundle.LoadAsync direct load a prefab from Assets folder? in Assets/Bundle folder has a prefab called "BGELement" , i did not want put it in to Resources folder and using Resource.Load to load it. the follow is my code ,but it make a error : NullReferenceException, the error line is that ab.LoadAsync()

 using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {

    void Start () {
        StartCoroutine(NewLoadBGElement ());
    }

    IEnumerator NewLoadBGElement () {
        string path = Application.dataPath + "/Bundle/BGElement";
        AssetBundle ab = new AssetBundle ();
        AssetBundleRequest abr = ab.LoadAsync(path, typeof(GameObject));
        yield return abr;
        GameObject newCube = Instantiate(abr.asset) as GameObject;
    }
}

Answer

MichaelTaylor3D picture MichaelTaylor3D · Nov 12, 2013

No you cant, but you can put them in the streaming assets folder as an asset bundle (You need Unity Pro to do this).

You can then use WWW class to "download" your files from the streaming asset folder. Just be sure to prepend your download path with "file:\"

WWW www = new WWW("file://" + Application.streamingAssetsPath + "/your file");

Note, if you copy or download files to your devices persistent data path, you can download them the same way using

Application.persistentDataPath

instead.

My suggestion, if you want you upload assets in real time is to export your prefabs as an AssetBundle and then stick them in your Streaming Assets Folder. You should them be able to load in the asset bundles in real time. You can also put the asset bundles on the server and download them through the web as well.

Example:

        public static IEnumerator DownloadFromStreamingAssetsFolder(string assetBundleName)
        {
            WWW file = new WWW("file://" + Application.streamingAssetsPath + assetBundleName);
            yield return file;
            //Do something with your download
        }