- Home /
BuildAssetBundle results in System.InvalidCastException
My code is posted below. You pass it a directory, and it should package all the assets in the directory into an AssetBundle. Instead, it crashes with an "System.InvalidCastException: Cannot cast from source type to destination type." error on the "BuildPipeline.BuildAssetBundle" line.
If I call "BuildAssetBundle(objs[0], null", everything works great. If I call "BuildAssetBundle(objs[any_number_up_to_length_of_array], null", everything works great. I can't figure out why Unity doesn't like my Object[] array, and why it won't let me build multiple assets into a bundle instead of just one at a time...
//Directory of assets to package into bundle var ab : String = "Assets/Path/To/Assets/To/Package/";
//Determine title for this bundle var offset : int = ab.Substring(0, ab.length-2).LastIndexOf("/") + 1; var title : String = ab.Substring(offset, ab.length - offset - 1) + ".unity3d";
//Iterate through each file to be built in this bundle var objArr : Array = new Array(); var files : String[] = System.IO.Directory.GetFiles(ab, "*", System.IO.SearchOption.AllDirectories); for(var file : String in files) objArr.Add(AssetDatabase.LoadMainAssetAtPath(file));
//Build Bundle! var objs : Object[] = objArr.ToBuiltin(Object); BuildPipeline.BuildAssetBundle(null, objs, title);
Answer by Aubrey-Falconer · Dec 10, 2009 at 07:25 PM
NCarter just solved this for me on the #Unity3D chat!
"Object" by default references System.Object and not UnityEngine.Object.
Explicitly referencing UnityEngine.Object resolved the issue.
This is either a bug or a very strange design decision in Unity's JS implementation...
Answer by Aubrey-Falconer · Dec 10, 2009 at 05:43 PM
Here's some code simplified as much as it could possibly be - I just don't understand how it can fail to run properly.
Debug.Log(file); //Assets/Whirlds/MarsAssets/Textures/Dirt.png Debug.Log(title); //Textures.unity3d
var objs : Object[] = new Object[1]; objs[0] = AssetDatabase.LoadMainAssetAtPath(file); BuildPipeline.BuildAssetBundle(null, objs, title); //System.InvalidCastException: Cannot cast from source type to destination type.