Unity3d File Based assetbundles on the iPhone
Let me start off by saying that unity3d is a really great game engine. let me also say that I wish the documentation was as great as the engine is. sadly, it's difficult to figure out some of the more powerful features of unity3d without significant trial and error.
Please note, that I have read that the usage of assetbundles on the iPhone can be Memory Intensive and may or may not fit your needs per your project. I am just putting this information here so that others can see how to do this. Pro tip: What this means to you? Profile the heck out of your code, pre-assetbundles and after integrating assetbundles.
Assumptions:
1. You know or are familiar unity3d 3.3.
2. You can code in C #.
3. You're an ace at creating prefabs in unity.
4. You're using unity3d 3.3 pro and iOS pro.
OK, if you're still feeling good, let's bounce into this how-.
Create the projectopen up a new project in unity3d and set it up for "iPhone" iOS. Feel free to name it whatever passes your way.
InProjectHierarchy, let's go ahead and create a simple directory structure as follows:
/Example project/
/Example project/iPhone/
/Example project/iPhone/objects/
/Example project/iPhone/materials/
Hit save after doing this and save your default scene and name it whatever you want. In my case, I named it "test ".
Though, This is a near complete looking example (image to the right), the basic structure shoshould look like the image to the right here.
Add at least one prefab to your project. I have added two prefabs here, "box" and "ABCD ". both are just tests and contain a cube prefab with a simple texture applied. make sure that the materials referenced by your prefabs have the following attributes. 1. they are named the same as the Prefab. (See the image above !). 2. they are stored in the materials folder underneath the iPhone folder.
Unityeditor coding time
When working on assetbundles, the first thing you have to do is generate them. unfortunately, unity3d does not have anything built in for generating these files stored t for a unityeditor API. the unityeditor script can only be run from inside the unity3d Editor tool. it typically appears as a menu item after the script has been successfully compiled. so if you can code, then you're in good shape.
Let's create the unityeditor script. Create a new C-sharp script in/Plugins/Folder (create it if it doesn't already exist) at the root of your project and name itMpcreateassetbundle. Copy and paste the following into it.Please note: some of this code was borrowed from Unity's own character customization tutorial on their website.
View code CSHARP
P. P1 {margin: 0.0px 0.0px 0.0px 0.0px; Font: 12.0px courier}
Span. Apple-tab-span {white-space: Pre}
Using system;
Using system. IO;
Using system. Collections. Generic;
Using unityeditor;
Using unityengine;
Using Object = unityengine. object;
Public class mpcreateassetbundle: monobehaviour {
Private Static string [] mpassetdir = new string [] {"iPhone", "iPad", "MacOSX", "PC"}; //, "universal "}; <-- not needed, use the/resources/folder.
[Menuitem ("Custom/monkey prism/create all assetbundles # & I")]
Public static void execute (){
Debug. Log ("creating assetbundles ");
Bool blnfound = false;
String currentdir = NULL;
Foreach (Object o in selection. getfiltered (typeof (object), selectionmode. deepassets )){
Blnfound = true;
If (O. Name. Contains ("@") continue; // animations!
String assetpath = assetdatabase. getassetpath (O );
If (! File. exists (assetpath )){
Currentdir = assetpath;
Continue; // files only.
}
// Only check those directories that we have specified in the mpassetdir
Debug. Log (assetpath );
String currentbuildtype = NULL;
Foreach (string s in mpassetdir ){
If (assetpath. Contains ("/" + S + "/")){
Currentbuildtype = s;
Break;
}
}
If (currentbuildtype = NULL) continue; // If the directory is not found to be one from the mpassetdir bail out.
String assetbundlename = NULL, genericname = NULL;
List <Object> toinclude = new list <Object> ();
// Generate pre-FABS for everything in the finished pre-fab directory.
If (O. GetType () = typeof (gameobject )){
Debug. Log ("gameobject" + currentdir );
String d = characterroot (gameobject) O );
D + = "Materials /";
Debug. Log (d );
List <material> materials = collectall <material> (d );
Debug. Log ("materials count =" + materials. Count );
Genericname = O. Name. tolower ();
Assetbundlename = currentbuildtype + "-prefab-" + genericname;
// Package up the prefabs in the iPhone directory.
Toinclude. Add (O );
// Do we need to add in a material? I think so.
Foreach (material m in materials ){
Debug. Log ("material name =" + M. Name );
If (M. Name. Contains (genericname )){
Toinclude. Add (m );
Debug. Log ("added a new material! ");
}
} // End foreach
}
If (assetbundlename = NULL) continue;
// Create a directory to store the generated assetbundles.
If (! Directory. exists (assetbundlepath ))
Directory. createdirectory (assetbundlepath );
// Delete existing assetbundles for current object
String [] existingassetbundles = directory. getfiles (assetbundlepath );
Foreach (string bundle in existingassetbundles ){
If (bundle. endswith (". assetbundle") & bundle. Contains ("/assetbundles/" + assetbundlename ))
File. Delete (bundle );
}
// Directories expected.
Debug. Log ("currentbuildtype =" + currentbuildtype );
// Path = assetbundlepath + bundlename + ". assetbundle ";
If (toinclude. Count> 0 ){
String Path = assetbundlepath + assetbundlename + ". assetbundle ";
Debug. Log (PATH );
If (currentbuildtype. Equals (mpassetdir [0]) | currentbuildtype. Equals (mpassetdir [1]) // iPhone & iPad
Buildpipeline. buildassetbundle (null, toinclude. toarray (), path, buildassetbundleoptions. collectdependencies, buildtarget. iPhone );
Else // todo: might need to condition further and might want to use an Enum with the conditional.
Buildpipeline. buildassetbundle (null, toinclude. toarray (), path, buildassetbundleoptions. collectdependencies );
}
} // End foreach
If (! Blnfound ){
Debug. Log ("No objects were found for building assets .");
}
}
Public static string assetbundlepath
{
Get {return "assetbundles" + path. directoryseparatorchar ;}
}
// This method loads all files at a certain path and
// Returns a list of specific assets.
Public static list <t> collectall <t> (string path) where T: Object
{
List <t> L = new list <t> ();
String [] files = directory. getfiles (PATH );
Foreach (string file in files)
{
If (file. Contains (". Meta") continue;
T asset = (t) assetdatabase. loadassetatpath (file, typeof (t ));
If (Asset = NULL) throw new exception ("asset is not" + typeof (t) + ":" + file );
L. Add (asset );
}
Return L;
}
// Returns the path to the directory that holds the specified fbx.
Static string characterroot (gameobject character)
{
String root = assetdatabase. getassetpath (character );
Return root. substring (0, root. lastindexof ('/') + 1 );
}
}
Once this is completed, you'll want to do two things.
1. Select (by moving your mouse over and left-clicking on it once)IPhoneFolder under "Example Project ".
2. Run the script as shown in the image:
So let's back up for a second and look at what we just did. we created a project, created some folders within the project, placed prefabs into the iPhone folder and created a unityeditor script. upon running this script, a new directory named "assetbundles" wocould be created.
This directory is not going to be visible to you until you open finder (on Mac) or Explorer (on Windows) as it is located on the file system. (See the image above ). inside this folder you shoshould see your prefab (s) named now:IPhone-prefab-<my prefab Name>. assetbundle. If you are seeing this, congratulations, you 've now created your own assetbundles uniquely per Prefab.
Generic gameobject and a simple script
If you 've come this far, great work! We're re nearly done.
Let's create a new gameobject underHierarchy.
Now we're re going to write a simple script to instantiate the assetbundles we assembled earlier. Create a new C-sharp script in/Plugins/Folder and name it "Example". copy and paste the following code into it:
View code CSHARP
P. P1 {margin: 0.0px 0.0px 0.0px 0.0px; Font: 12.0px courier}
Span. Apple-tab-span {white-space: Pre}
Using system;
Using unityengine;
Using system. collections;
Public Class Example: monobehaviour {
Private WWW;
Private assetbundlerequest gameobjectrequest;
// Use this for initialization
Ienumerator start (){
// Todo: change the name of the file below !!!
String strpath = "file: //" + application. datapath + "/../assetbundles/iphone-prefab-box.assetbundle ";
Debug. Log (strpath );
WWW = new WWW (strpath );
Yield return WWW;
/* Todo: Change the name "box" to match the name of your prefab that you compiled into the assetbundle on Step 1 .*/
Assetbundlerequest request = www. assetbundle. loadasync ("box", typeof (gameobject ));
Yield return request;
Instantiate (request. Asset, new vector3 (3f, 0f, 0f), quaternion. Identity );
Instantiate (request. Asset, new vector3 (0f, 0f, 0f), quaternion. Identity );
Instantiate (request. Asset, new vector3 (-3f, 0f, 0f), quaternion. Identity );
Www. assetbundle. Unload (true );
}
Void Update (){}
}
Note:Make sure to change the todo line in the code to match your file name! If you don't do this, it might not work!
We're re nearly done! Drag your example. CS script onto the gameobject you created earlier. Here is how my project looks:
Build time
We're re now going to build this codebase so that you can run it on your iOS device for testing. i'm going to skip the painful steps of creating a code signing Certificate and all that jazz. we're re instead going to focus on how to get the actual assetbundle onto your iOS device in an area that will be accessible to the "application. datapath "call in your code!
1. Build the unity project for IOS.
2. xcode shoshould automatically open.
3. Within xcode you are going to need to tell it about your assetbundles folder! Open up finder or explorer and locate the assetbundles folder that was generated by the unityeditor script we discussed earlier.
4. Drag and Drop the assetbundles folder into xcode at the root of the IOS project. (You should see a prompt as follows)
5. Click "finish ".
This will then look something like this:
6. Build the code using xcode and run it on your iOS device.
If everything works properly, you shoshould see one of the prefabs instantiate on your iOS screen. That is all there is to it! I think you'll find that this isn't as bad as one might imagine, but it does require some serous fishing around in code examples and heavily crawling the unity forums. the only way I figured this out was by trial and error, heavy amounts of debug. log CILS and 3 pots of coffee. i'm now going to go and grind my teeth on my level editor.
Edit: I have one of my original Forum posts here as well regarding this issue. unity3d Forum
//////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// //
Http://www.chrisdanielson.com/2011/05/03/unity3d-file-assetbundles-on-the-iphone/