2
votes

i am trying to load an already created FBX object into the scene at runtime, i searched around and found that assetbundle can be used to do so. I tried this code but it doesnt seem to instantiate the object in the scene and neither does it pop an error.

Here is the code

using System;
using UnityEngine;
using System.Collections;

public class CachingLoadExample : MonoBehaviour {
    public string BundleURL;
    public string AssetName;
    public int version;

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

    IEnumerator DownloadAndCache (){
       // Wait for the Caching system to be ready
       while (!Caching.ready)
            yield return null;

        // 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)
                throw new Exception("WWW download had an error:" + www.error);
            AssetBundle bundle = www.assetBundle;
            if (AssetName == "")
                Instantiate(bundle.mainAsset);
            else
                Instantiate(bundle.Load(AssetName));
            // Unload the AssetBundles compressed contents to conserve memory
                    bundle.Unload(false);

        } // memory is freed from the web stream (www.Dispose() gets called implicitly)
    }
}

I added a new empty game object, dragged the C# code to that game object, supplied the asset bundle link "file://C:/Users/Sahibzada/Documents/New Unity Project/Assets/100777102370.FBX" but no luck

Can someone please guide me, whats wrong with the code, i am totally new with scripting in Unity, Thanks

1
Define "no luck". What specifically isn't happening as expected? Are you seeing any error messages? Did you check the console? Are you sure you're using Unity Pro? - rutter
No error pops up, and neither does an object gets added to the scene, the FBX object i am referring to in the BundleURL. - Junaid Noor
Perhaps Caching.isReady is never returning true? Also: are you sure you're using Unity Pro? It's required for use with asset bundles. - rutter

1 Answers

2
votes

Create a folder named AssetBundles inside your Assets folder, then you need to create the AssetBundle of your FBX with an Editor script as show in: http://docs.unity3d.com/Manual/BuildingAssetBundles.html

using UnityEditor;

public class CreateAssetBundles
{
     [MenuItem ("Assets/Build AssetBundles")]
     static void BuildAllAssetBundles ()
     {
         BuildPipeline.BuildAssetBundles ("Assets/AssetBundles");
     }
}

Lastly you need to introduce, in the BundleURL the URL to the new AssetsBundle:

"file://C:/Users/Sahibzada/Documents/New Unity Project/Assets/AssetsBundles/yourassetbundle" 

and on the AssetName you need to introduce "yourassetbundle"

I also recommend not having paths with spaces, this can also be an issue.