WWWの多重読み込みとUnloadメモ
AssetBundleなどリソースをWWWクラスでロードする場合、多重読み込みとかUnloadとか色々めんどくさい上にLoadFromCacheOrDownloadとnew WWW()で挙動が変わってくるのでメモ。あ、Unity4.6の話です。
まずは正常系
同一URLを読み込んでいるが、適切なタイミングでUnloadすれば問題は起きない。
var www = WWW.LoadFromCacheOrDownload ("smpl.unity3d",1);
yield return www;
Debug.Log (www.error);//エラーなし
Instantiate (www.assetBundle.mainAsset);//表示
www.assetBundle.Unload (false);//ここでunload
var www2 = WWW.LoadFromCacheOrDownload ("smpl.unity3d",1);
yield return www2;
Debug.Log (www2.error);//エラーなし
Debug.Log (www2.assetBundle.mainAsset);//name取得
Instantiate (www2.assetBundle.mainAsset);//表示
6行目で
www.assetBundle.Unload (false);
しているが、2度目のLoadFromCacheOrDownloadまでに必須で実行。
例えば以下のタイミングだとエラーが出る
var www2 = WWW.LoadFromCacheOrDownload ("smpl.unity3d",1);
www.assetBundle.Unload (false);//遅いunload
yield return www2;
Debug.Log (www2.error);//Cannot load cached AssetBundle. A file of the same name is already loaded from another AssetBundle.
Debug.Log (www2.assetBundle.mainAsset);//You are trying to load data from a www stream which had the following error when downloading.
Instantiate (www2.assetBundle.mainAsset);//NullReferenceException: Object reference not set to an instance of an object
次にnew WWWな場合
var www = new WWW ("smpl.unity3d");
yield return www;
Debug.Log (www.error);//エラーなし
Instantiate (www.assetBundle.mainAsset);//表示される
var www2 = new WWW ("smpl.unity3d");
yield return www2;
Debug.Log (www2.error);//エラーなし
www.assetBundle.Unload (false);//ここでunload
Debug.Log (www2.assetBundle.mainAsset);//name取得
Instantiate (www2.assetBundle.mainAsset);//表示される
11行目になってようやくUnload実行でもok。なんとwww2.assetBundle.mainAssetを参照するまで問題なく動作する。さすがにそれ以上粘るとnull pointer系のエラーが出ます。
Debug.Log (www2.assetBundle.mainAsset);//The asset bundle 'hoge' can't be loaded because another asset bundle with the same files are already loaded www.assetBundle.Unload (false);//ここでunload Instantiate (www2.assetBundle.mainAsset);//NullReferenceException: Object reference not set to an instance of an object
あくまでもUnity4.6かつMacエディター上での挙動なので精査してませんが、実機でも同じようなもんじゃないかと。相変わらずネットワーク周りは貧弱この上ない。Unity5で改善されたって話だけど期待していいのだろうか...


