Can't get_datapath to work in a IEnumerator. Receiving unity error. Trying to asyncload asset bundle

I get these two errors when attempting to do so.

get_dataPath is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'CachingLoadAssetBundles'.
    See "Script Serialization" page in the Unity Manual for further details.
    UnityEngine.Application:get_dataPath()
    CachingLoadAssetBundles:.cctor() (at Assets/!Alpenhorn/Scripts/CachingLoadAssetBundles.cs:9)
   
UnityException: get_dataPath is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'CachingLoadAssetBundles'.
    See "Script Serialization" page in the Unity Manual for further details.
    CachingLoadAssetBundles..cctor () (at Assets/!Alpenhorn/Scripts/CachingLoadAssetBundles.cs:9)
    Rethrow as TypeInitializationException: An exception was thrown by the type initializer for CachingLoadAssetBundles

Here is the code that I am trying to make work. I’ve grabbed a lot of it from the doc’s and am attempting to modify it so it will go through the list of assetbundles and load them async.

using System;
using UnityEditor;

public class CachingLoadAssetBundles : MonoBehaviour {

    public static string BundleURL = Application.dataPath + "/!AlpenhornAssetBundles";
    public static List<string> AssetBundleList = new List<string>();
    public static int version = 0;
    public static WWW www = WWW.LoadFromCacheOrDownload(BundleURL, version);

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

    static void GetNames()
    {
        var names = AssetDatabase.GetAllAssetBundleNames();
        foreach (var name in names)
        {
            AssetBundleList.Add(name);
        }
    }

    //IEnumerator Start()
    //{
    //    while (!Caching.ready)
    //        yield return null;
    //    // Start a download of the given URL
    //    WWW www = WWW.LoadFromCacheOrDownload(BundleURL, 0);

    //    // Wait for download to complete
    //    yield return www;

    //    // Load and retrieve the AssetBundle
    //    AssetBundle bundle = www.assetBundle;

    //    // Load the object asynchronously
    //    AssetBundleRequest request = bundle.LoadAssetAsync("myObject", typeof(GameObject));

    //    // Wait for completion
    //    yield return request;

    //    // Get the reference to the loaded object
    //    GameObject obj = request.asset as GameObject;

    //    // Unload the AssetBundles compressed contents to conserve memory
    //    bundle.Unload(false);

    //    // Frees the memory from the web stream
    //    www.Dispose();
    //}

    //public static void Awake()
    //{
    //    StartCoroutine(Start(www));
    //}

    IEnumerator Start()
    {
        // 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))
        using (www)
        {
            yield return www;
            if (www.error != null)
            {
                throw new Exception("WWW download had an error:" + www.error);
            }

            AssetBundle bundle = www.assetBundle;

            foreach (var assetBundleList in AssetBundleList)
            {
                AssetBundleRequest requestAssetBundle = bundle.LoadAssetAsync(assetBundleList, typeof(GameObject));
                yield return requestAssetBundle;
                GameObject GO = requestAssetBundle.asset as GameObject;


                //if (assetBundleList == "")
                //{
                //    Instantiate(bundle.mainAsset);
                //}
                //else
                //{
                //    Instantiate(bundle.LoadAsset(assetBundleList));
                //}
                // Unload the AssetBundles compressed contents to conserve memory
                bundle.Unload(false);

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

I’m not sure what to do here. I’m trying to make sure i resolve the path in the _data folder when you build the game so I can throw in the assetbundles in there. Since this path will vary between everyone, I don’t know what the alternative way could be. I’m wanting to load the assetbundles off disk, not www.

It’s not the IEnumerator that’s causing it, it’s this line here:

public static string BundleURL = Application.dataPath + "/!AlpenhornAssetBundles";

This line of code will operate the first time the class is accessed because it’s static (during ‘constructor’ essentially, static constructor that is).

During a constructor method you can access certain parts of the Unity API (for various reasons).

So don’t put that line there.

Have the string defined during Awake, or at some other time.

Oh and this one:

public static WWW www = WWW.LoadFromCacheOrDownload(BundleURL, version);

Yep, that ones going to give you trouble as well!

Thank you for getting back with me. I have to have the string static, other wise the WWW variable gives me a warning.

But when I add the variable to Awake(), this is what I see in my VSC2015 Screenshot - 0007d3a3849630e1bf4c67ce20d381db - Gyazo

Oh i figured out my above issue. I have to make them global still, and just set them equal to what they need to be in awake. I can’t declare them in awake!

**EDIT, figured i’d put in the new code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
#if UNITY_EDITOR
using UnityEditor;
#endif

public class CachingLoadAssetBundles : MonoBehaviour {

    public string BundleURL; // = Application.dataPath + "/!AlpenhornAssetBundles";
    public static List<string> AssetBundleList = new List<string>();
    public static int version = 0;
    public WWW www; // = WWW.LoadFromCacheOrDownload(BundleURL, version);

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

    static void GetNames()
    {
        var names = AssetDatabase.GetAllAssetBundleNames();
        foreach (var name in names)
        {
            AssetBundleList.Add(name);
        }
    }

    //IEnumerator Start()
    //{
    //    while (!Caching.ready)
    //        yield return null;
    //    // Start a download of the given URL
    //    WWW www = WWW.LoadFromCacheOrDownload(BundleURL, 0);

    //    // Wait for download to complete
    //    yield return www;

    //    // Load and retrieve the AssetBundle
    //    AssetBundle bundle = www.assetBundle;

    //    // Load the object asynchronously
    //    AssetBundleRequest request = bundle.LoadAssetAsync("myObject", typeof(GameObject));

    //    // Wait for completion
    //    yield return request;

    //    // Get the reference to the loaded object
    //    GameObject obj = request.asset as GameObject;

    //    // Unload the AssetBundles compressed contents to conserve memory
    //    bundle.Unload(false);

    //    // Frees the memory from the web stream
    //    www.Dispose();
    //}

    //public static void Awake()
    //{
    //    StartCoroutine(Start(www));
    //}

    void Awake()
    {
        BundleURL = Application.dataPath + "/!AlpenhornAssetBundles";
        www = WWW.LoadFromCacheOrDownload(BundleURL, version);
    }

    IEnumerator Start()
    {
        // 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))
        using (www)
        {
            yield return www;
            if (www.error != null)
            {
                throw new Exception("WWW download had an error:" + www.error);
            }

            AssetBundle bundle = www.assetBundle;

            foreach (var assetBundleList in AssetBundleList)
            {
                AssetBundleRequest requestAssetBundle = bundle.LoadAssetAsync(assetBundleList, typeof(GameObject));
                yield return requestAssetBundle;
                GameObject GO = requestAssetBundle.asset as GameObject;


                //if (assetBundleList == "")
                //{
                //    Instantiate(bundle.mainAsset);
                //}
                //else
                //{
                //    Instantiate(bundle.LoadAsset(assetBundleList));
                //}
                // Unload the AssetBundles compressed contents to conserve memory
                bundle.Unload(false);

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

Can I get some feed back on this Updated script? Is this a step in the right direction or not? Will this script, as is, async load my assetbundles??

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
//#if UNITY_EDITOR
using UnityEditor;
//#endif

public class CachingLoadAssetBundles : MonoBehaviour {

    public string BundleURL; // = Application.dataPath + "/!AlpenhornAssetBundles";
    public static List<string> AssetBundleList = new List<string>();
    public static int version = 0;
    public WWW www; // = WWW.LoadFromCacheOrDownload(BundleURL, version);

    static void GetNames()
    {
        var names = AssetDatabase.GetAllAssetBundleNames();
        foreach (var name in names)
        {
            AssetBundleList.Add(name);
        }
    }

    void Awake()
    {
        BundleURL = "file://" + Application.dataPath + "/!AlpenhornAssetBundles";
        www = WWW.LoadFromCacheOrDownload(BundleURL, version);
        GetNames();
    }

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

        using (www)
        {
            yield return www;
            if (www.error != null)
            {
                throw new Exception("WWW download had an error:" + www.error);
            }

            AssetBundle bundle = www.assetBundle;

            foreach (var assetBundleList in AssetBundleList)
            {
                AssetBundle.LoadFromFileAsync(assetBundleList);
                Debug.Log("The loaded asset was: " + assetBundleList);

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

So turns out I guess my GetNames function only works in the editor because I have to uncomment the #if & #endif lines 5&7.

If this will only run in the editor, how can i get all the asset bundle names outside of the editor? AssetDatabase is a method of UnityEditor.

Assets/!Alpenhorn/Scripts/CachingLoadAssetBundles.cs(6,7): error CS0246: The type or namespace name `UnityEditor' could not be found. Are you missing an assembly reference?