Unity scene empty after loading Asset Bundles - unity3d

I'm creating an AssetBundle in Unity containing one scene with the following code:
string[] scenes = {"Assets/Scenes/main.unity"};
BuildPipeline.BuildStreamedSceneAssetBundle( scenes , "main.unity3d", EditorUserBuildSettings.activeBuildTarget);
I have an empty intro scene that loads the main scene at the start of the app on iOS:
using (WWW www = WWW.LoadFromCacheOrDownload (url + "main.unity3d", 0)) {
while (!www.isDone) {
yield return null;
}
//check if server response is an error
if (www.error != null) {
throw new Exception ("WWW download had an error: " + www.error);
}
//Load the asset bundle
AssetBundle bundle = www.assetBundle;
bundle.LoadAllAssets ();
}
Application.LoadLevel ("main")
The problem is that the main scene is correctly loaded, but the 3D objects in it ( FBX files + textures ) can not be seen . The main scene has no scripts , only 3D objects , including simple cubes of Unity , which have been stored as prefabs in the Assets folder .
What could be wrong , that the 3D data are not displayed ? The Asset Bundle itself has around 20MB , which by size definitely the 3D objects should contain . I use Unity 5.2.4 and it is only a problem in iOS , Android is working and the objects are displayed normally .

I found the solution. You have to turn off "Strip Engine Code" in Unity

Related

Unity assetbundle scene unload

I have created few assetbundle scenes for my project. Now I am downloading the assetbundles and able to load scenes. Here the problem is that when I run a scene and exit from that and try to reload the same scene once again, it is giving an error like
"The Assetbundle mywebsite.com/bundles/assetbundle.unity3d can't be loaded because another AssetBundle with the same files is already loaded."
Im not able to open the scene for second time. Can anyone tell the problem and help me to resolve?! Thanks in advance.
Im adding the code here:
IEnumerator sceneLoad()
{
WWW www = WWW.LoadFromCacheOrDownload(myurl,version);
while (!www.isDone)
{
msg.text = "Downloading...";
float progress = Mathf.Clamp01 (www.progress / .9f);
progressslide.value = progress;
float val = progress * 100f;
double value = System.Math.Round (val, 2);
progresstext.text = value + "%";
Debug.Log ("Progress " + progresstext.text);
yield return null;
}
bundle = www.assetBundle;
msg.text = "Opening Scene...";
progressslide.gameObject.SetActive (false);
progresstext.gameObject.SetActive (false);
string[] scenepath = bundle.GetAllScenePaths ();
Debug.Log (scenepath [0]);
var async = SceneManager.LoadSceneAsync(System.IO.Path.GetFileNameWithoutExtension (scenepath [0]));
yield return null;
bundle.Unload (false);
}
The above code is perfectly working on unity engine in my pc but when I build apk and run on phone, the progress bar is not working but bundle is downloading and scene is opening. Later when I exit the scene, comes to my app main page and again open the same scene, it was showing the error as
"The Assetbundle mywebsite.com/bundles/assetbundle.unity3d can't be loaded because another AssetBundle with the same files is already loaded."
I am using Vuforia in the downloaded scene.
You should unload the loadded asset bundle when you exit the scene.
Maybe you will find this proper asset bundle guide.

Load binary data from the resources folder [duplicate]

I have am developing a HoloLens project that needs to reference .txt files. I have the files stored in Unity's 'Resources' folder and have them working perfectly fine (when run via Unity):
string basePath = Application.dataPath;
string metadataPath = String.Format(#"\Resources\...\metadata.txt", list);
// If metadata exists, set title and introduction strings.
if (File.Exists(basePath + metadataPath))
{
using (StreamReader sr = new StreamReader(new FileStream(basePath + metadataPath, FileMode.Open)))
{
...
}
}
However, when building the program for HoloLens deployment, I am able to run the code but it doesn't work. None of the resources show up and when examining the HoloLens Visual Studio solution (created by selecting build in Unity), I don't even see a resources or assets folder. I am wondering if I am doing something wrong or if there was a special way to deal with such resources.
Also with image and sound files...
foreach (string str in im)
{
spriteList.Add(Resources.Load<Sprite>(str));
}
The string 'str' is valid; it works absolutely fine with Unity. However, again, it's not loading anything when running through the HoloLens.
You can't read the Resources directory with the StreamReader or the File class. You must use Resources.Load.
1.The path is relative to any Resources folder inside the Assets folder of your project.
2.Do not include the file extension names such as .txt, .png, .mp3 in the path parameter.
3.Use forward slashes instead of back slashes when you have another folder inside the Resources folder. backslashes won't work.
Text files:
TextAsset txtAsset = (TextAsset)Resources.Load("textfile", typeof(TextAsset));
string tileFile = txtAsset.text;
Supported TextAsset formats:
txt .html .htm .xml .bytes .json .csv .yaml .fnt
Sound files:
AudioClip audio = Resources.Load("soundFile", typeof(AudioClip)) as AudioClip;
Image files:
Texture2D texture = Resources.Load("textureFile", typeof(Texture2D)) as Texture2D;
Sprites - Single:
Image with Texture Type set to Sprite (2D and UI) and
Image with Sprite Mode set to Single.
Sprite sprite = Resources.Load("spriteFile", typeof(Sprite)) as Sprite;
Sprites - Multiple:
Image with Texture Type set to Sprite (2D and UI) and
Image with Sprite Mode set to Multiple.
Sprite[] sprite = Resources.LoadAll<Sprite>("spriteFile") as Sprite[];
Video files (Unity >= 5.6):
VideoClip video = Resources.Load("videoFile", typeof(VideoClip)) as VideoClip;
GameObject Prefab:
GameObject prefab = Resources.Load("shipPrefab", typeof(GameObject)) as GameObject;
3D Mesh (such as FBX files)
Mesh model = Resources.Load("yourModelFileName", typeof(Mesh)) as Mesh;
3D Mesh (from GameObject Prefab)
MeshFilter modelFromGameObject = Resources.Load("yourGameObject", typeof(MeshFilter)) as MeshFilter;
Mesh loadedMesh = modelFromGameObject.sharedMesh; //Or design.mesh
3D Model (as GameObject)
GameObject loadedObj = Resources.Load("yourGameObject") as GameObject;
//MeshFilter meshFilter = loadedObj.GetComponent<MeshFilter>();
//Mesh loadedMesh = meshFilter.sharedMesh;
GameObject object1 = Instantiate(loadedObj) as GameObject;
Accessing files in a sub-folder:
For example, if you have a shoot.mp3 file which is in a sub-folder called "Sound" that is placed in the Resources folder, you use the forward slash:
AudioClip audio = Resources.Load("Sound/shoot", typeof(AudioClip)) as AudioClip;
Asynchronous Loading:
IEnumerator loadFromResourcesFolder()
{
//Request data to be loaded
ResourceRequest loadAsync = Resources.LoadAsync("shipPrefab", typeof(GameObject));
//Wait till we are done loading
while (!loadAsync.isDone)
{
Debug.Log("Load Progress: " + loadAsync.progress);
yield return null;
}
//Get the loaded data
GameObject prefab = loadAsync.asset as GameObject;
}
To use: StartCoroutine(loadFromResourcesFolder());
If you want to load text file from resource please do not specify file extension
just simply follow the below given code
private void Start()
{
TextAsset t = Resources.Load<TextAsset>("textFileName");
List<string> lines = new List<string>(t.text.Split('\n'));
foreach (string line in lines)
{
Debug.Log(line);
}
}
debug.Log can print all the data that are available in text file
You can try to store your text files in streamingsasset folder. It works fine in my project

JSONReaderException when deploying on hololens [duplicate]

I have am developing a HoloLens project that needs to reference .txt files. I have the files stored in Unity's 'Resources' folder and have them working perfectly fine (when run via Unity):
string basePath = Application.dataPath;
string metadataPath = String.Format(#"\Resources\...\metadata.txt", list);
// If metadata exists, set title and introduction strings.
if (File.Exists(basePath + metadataPath))
{
using (StreamReader sr = new StreamReader(new FileStream(basePath + metadataPath, FileMode.Open)))
{
...
}
}
However, when building the program for HoloLens deployment, I am able to run the code but it doesn't work. None of the resources show up and when examining the HoloLens Visual Studio solution (created by selecting build in Unity), I don't even see a resources or assets folder. I am wondering if I am doing something wrong or if there was a special way to deal with such resources.
Also with image and sound files...
foreach (string str in im)
{
spriteList.Add(Resources.Load<Sprite>(str));
}
The string 'str' is valid; it works absolutely fine with Unity. However, again, it's not loading anything when running through the HoloLens.
You can't read the Resources directory with the StreamReader or the File class. You must use Resources.Load.
1.The path is relative to any Resources folder inside the Assets folder of your project.
2.Do not include the file extension names such as .txt, .png, .mp3 in the path parameter.
3.Use forward slashes instead of back slashes when you have another folder inside the Resources folder. backslashes won't work.
Text files:
TextAsset txtAsset = (TextAsset)Resources.Load("textfile", typeof(TextAsset));
string tileFile = txtAsset.text;
Supported TextAsset formats:
txt .html .htm .xml .bytes .json .csv .yaml .fnt
Sound files:
AudioClip audio = Resources.Load("soundFile", typeof(AudioClip)) as AudioClip;
Image files:
Texture2D texture = Resources.Load("textureFile", typeof(Texture2D)) as Texture2D;
Sprites - Single:
Image with Texture Type set to Sprite (2D and UI) and
Image with Sprite Mode set to Single.
Sprite sprite = Resources.Load("spriteFile", typeof(Sprite)) as Sprite;
Sprites - Multiple:
Image with Texture Type set to Sprite (2D and UI) and
Image with Sprite Mode set to Multiple.
Sprite[] sprite = Resources.LoadAll<Sprite>("spriteFile") as Sprite[];
Video files (Unity >= 5.6):
VideoClip video = Resources.Load("videoFile", typeof(VideoClip)) as VideoClip;
GameObject Prefab:
GameObject prefab = Resources.Load("shipPrefab", typeof(GameObject)) as GameObject;
3D Mesh (such as FBX files)
Mesh model = Resources.Load("yourModelFileName", typeof(Mesh)) as Mesh;
3D Mesh (from GameObject Prefab)
MeshFilter modelFromGameObject = Resources.Load("yourGameObject", typeof(MeshFilter)) as MeshFilter;
Mesh loadedMesh = modelFromGameObject.sharedMesh; //Or design.mesh
3D Model (as GameObject)
GameObject loadedObj = Resources.Load("yourGameObject") as GameObject;
//MeshFilter meshFilter = loadedObj.GetComponent<MeshFilter>();
//Mesh loadedMesh = meshFilter.sharedMesh;
GameObject object1 = Instantiate(loadedObj) as GameObject;
Accessing files in a sub-folder:
For example, if you have a shoot.mp3 file which is in a sub-folder called "Sound" that is placed in the Resources folder, you use the forward slash:
AudioClip audio = Resources.Load("Sound/shoot", typeof(AudioClip)) as AudioClip;
Asynchronous Loading:
IEnumerator loadFromResourcesFolder()
{
//Request data to be loaded
ResourceRequest loadAsync = Resources.LoadAsync("shipPrefab", typeof(GameObject));
//Wait till we are done loading
while (!loadAsync.isDone)
{
Debug.Log("Load Progress: " + loadAsync.progress);
yield return null;
}
//Get the loaded data
GameObject prefab = loadAsync.asset as GameObject;
}
To use: StartCoroutine(loadFromResourcesFolder());
If you want to load text file from resource please do not specify file extension
just simply follow the below given code
private void Start()
{
TextAsset t = Resources.Load<TextAsset>("textFileName");
List<string> lines = new List<string>(t.text.Split('\n'));
foreach (string line in lines)
{
Debug.Log(line);
}
}
debug.Log can print all the data that are available in text file
You can try to store your text files in streamingsasset folder. It works fine in my project

Cannot load an Asset Bundle

I created an asset bundle from an .fbx file. Then; I use this code for loading it into a very simple unity project
public class k : MonoBehaviour {
public string url;
// Use this for initialization
public string AssetName;
void Start()
{
}
IEnumerator DownloadAndCache(string bundleURL)
{
while (!Caching.ready)
yield return null;
using (WWW www = WWW.LoadFromCacheOrDownload(bundleURL, 1))
{
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.LoadAsset(AssetName));
bundle.Unload(false);
}
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.D))
StartCoroutine(DownloadAndCache(url));
}
}
but always is having the next issue
and I don't understand. Since i'm passing a valid local url in the next format :
file:///c:/asset/robot.unity3d
please help
A file with a unity3d extension isn't usually an AssetBundle.
To have an AssetBundle with the model in it you have to:
Import the model in Unity
Select the imported model so you see its properties in the Inspector
At the bottom of the Inspector there is a little interface to create and select AssetBundles (this way the model will be assigned to the selected AssetBundle)
After assigning every asset to their AssetBundle, you need to build the Bundles
Put the bundles files on a server or in the StreamingAssets folder and use their URL
AssetBundle management in Unity is still a painfull process so I suggest you to thoroughly read the Guide to AssetBundles and Resources.
There is also an AssetBundleManager here but I find it's code is a mess.
It's buggy and almost impossible to decipher: I ended up writing my own so I can't really suggest you to use it yet (I linked it because it might get better in the future).
Try calling bundle.GetAllAssetNames() to see what is inside the bundle before trying to instantiate anything.
AssetBundle bundle = www.assetBundle;
foreach(var name in bundle.GetAllAssetNames()){
Debug.Log(name);
}
mainAsset may be null depending on how the AssetBundle was created, so maybe that is what happening here, does it gives you the null exception if you try loading assets by name?

Unity5 Building Asset Bundles with scenes

I am trying to create an asset bundle with scenes. This is what I did in unity4
[MenuItem("Bundle/Create ios Scene SceneLoader")]
static void iosBuild(){
string[] levels = new string []{"Assets/Scenes/01 SceneLoader.unity", "Assets/Scenes/02 Level1.unity","Assets/Scenes/02 Level2.unity" ,"Assets/Scenes/02 Level3.unity"};
BuildPipeline.BuildStreamedSceneAssetBundle( levels, "Assets/Bundles/bundle-ios.unity3d", BuildTarget.iOS);
}
After that I load my bundle via this code:
using(WWW www = WWW.LoadFromCacheOrDownload (url, 0)){
while(!www.isDone){
status.text = "loading \n" + (www.progress * 100).ToString() + "%";
yield return null;
}
yield return www;
//check if server response is an error
if (www.error != null){
throw new Exception("WWW download had an error: " + url + " " + www.error);
}
//Load the asset bundle
AssetBundle bundle = www.assetBundle;
//obsolete bundle.LoadAll();
bundle.LoadAllAssets();
Application.LoadLevel ("01 SceneLoader");
}
This code worked in unity4, but now, when I load my Scene, all the script references are missing. Objects are in the scene but no scripts. Also, unity tells me that BuildStreamedSceneAssetBundle is obsolete. So my question is, why aren't my script references in the core scene ? So that when I load an asset bundle, all the scripts aren't missing. Also my NGUI Atlas that I use in the loaded scene is missing.
Would be glad if someone has an idea!
EDIT: the first string in "levels" will have all script references. How is that possible ?
I think this problem is unity bug.
My project has same problem.
I found solution, but it's very inconvenient.
If you must use scene asset bundle,
make one asset bundle per one scene.
string[] level1 = new string []{"Assets/Scenes/01 SceneLoader.unity"};
string[] level2 = new string []{"Assets/Scenes/02 Level1.unity"};
.....
BuildPipeline.BuildStreamedSceneAssetBundle( level1, "Assets/Bundles/bundle-ios1.unity3d", BuildTarget.iOS);
BuildPipeline.BuildStreamedSceneAssetBundle( level2, "Assets/Bundles/bundle-ios2.unity3d", BuildTarget.iOS);
.....
I used "BuildPipeline.BuildAssetBundles" func at Unity5.
But I think that "BuildPipeline.BuildStreamedSceneAssetBundle" and "BuildPipeline.BuildAssetBundles" is similar.