I've created the ability to download and store an asset bundle to my device. Now I'm trying to load an assetbundle from an already downloaded bundle.
I'm saving the bundle like so:
IEnumerator Start ()
{
WWW urlToLoad = new WWW(url);
yield return urlToLoad;
//read in JSON data
string jsonContents = urlToLoad.text;
var n = JSON.Parse(jsonContents);
jsonURL = n["data"][0];
Debug.Log(jsonURL.ToString());
// split up the json and get last element in teh array
string[] splitJSONURL = jsonURL.Split('/');
string bundle = splitJSONURL[splitJSONURL.Length - 1];
Debug.Log("array: " + bundle.ToString());
//StartCoroutine( DownloadAndCache());
// save bundle to the application folder
string path = Application.persistentDataPath + "/" + bundle;
Debug.Log("Path: " + path);
SaveBytesAsFile(path, urlToLoad.bytes);
savedBundleString = Application.persistentDataPath + "/" + bundle;
}
Next I'm trying to load the bundle like this:
IEnumerator LoadLocalBundle(string filePath)
{
print("Loading from local file..." + filePath);
WWW www = new WWW(filePath);
yield return www;
if(www.error == null)
{
print ("loaded local bundle - instantiating :: " + www.assetBundle.mainAsset.name);
GameObject bundleInstance = (GameObject)Instantiate(www.assetBundle.mainAsset);
assetBundle = www.assetBundle;
}
}
void OnGUI()
{
if (GUI.Button(new Rect(10, 70, 50, 30), "Click"))
{
StartCoroutine( LoadLocalBundle(savedBundleString));
}
}
However, when I run this, nothing loads.
What am I doing wrong?
Related
How can I convert UnityEngine.Object[] to Texture2D[] ?
I am using this script :
void Start()
{
string dataFileName = "skins";
string tempPath = Path.Combine(Application.persistentDataPath, "AssetData");
tempPath = Path.Combine(tempPath, dataFileName + ".unity3d");
StartCoroutine(LoadObject(tempPath).GetEnumerator());
}
IEnumerable LoadObject(string path)
{
Debug.Log("Loading...");
AssetBundleCreateRequest bundle = AssetBundle.LoadFromFileAsync(path);
yield return bundle;
AssetBundle myLoadedAssetBundle = bundle.assetBundle;
if (myLoadedAssetBundle == null)
{
Debug.Log("Failed to load AssetBundle!");
yield break;
}
AssetBundleRequest request = myLoadedAssetBundle.LoadAllAssetsAsync();
yield return request;
Texture2D[] obj = request.allAssets as Texture2D[];
var path2 = Application.persistentDataPath + "/Item Images/";
if (!Directory.Exists(Path.GetDirectoryName(path2)))
{
Directory.CreateDirectory(Path.GetDirectoryName(path2));
}
foreach (Texture2D s in obj)
{
byte[] itemBGBytes = s.EncodeToPNG();
File.WriteAllBytes(Application.persistentDataPath + "/Item Images/" + s.name + ".png", itemBGBytes);
}
myLoadedAssetBundle.Unload(false);
}
Conversion of Object[] to Texture2D[] is not working. I got this script from the stackoverflow post -> Download AssetBundle in hard disk
If request.allAssets returns object[] which you know are Texture2D , then you can try:
object[] aObj = request.allAssets;
Texture2D[] aT2D = Array.ConvertAll(aObj, x => (Texture2D) x);
Right now, it seems UnityWebRequest.GetAssetBundledownload asset to RAM and load. Is there anyway to download to hard disk to load?
This is not really complicated. Handle it like a normal file you would download from the internet but save it with the ".unity3d" extension.
1.Download the AssetBundle as a normal file by making a request with UnityWebRequest.
UnityWebRequest www = UnityWebRequest.Get(url);
yield return www.Send();
2.Retrieve the byte array data with DownloadHandler.data then save it to Application.persistentDataPath/yourfolder/filename.unity3d. Make sure that the extension is ".unity3d".
File.WriteAllBytes(handle.data, data);
That's it.
3.To load the data, use AssetBundle.LoadFromFile or AssetBundle.LoadFromFileAsync:
AssetBundleCreateRequest bundle = AssetBundle.LoadFromFileAsync(path);
If still confused, here is what the thing should look like. You may need to make some modification:
Download and Save:
IEnumerator downloadAsset()
{
string url = "http://url.net/YourAsset.unity3d";
UnityWebRequest www = UnityWebRequest.Get(url);
DownloadHandler handle = www.downloadHandler;
//Send Request and wait
yield return www.Send();
if (www.isError)
{
UnityEngine.Debug.Log("Error while Downloading Data: " + www.error);
}
else
{
UnityEngine.Debug.Log("Success");
//handle.data
//Construct path to save it
string dataFileName = "WaterVehicles";
string tempPath = Path.Combine(Application.persistentDataPath, "AssetData");
tempPath = Path.Combine(tempPath, dataFileName + ".unity3d");
//Save
save(handle.data, tempPath);
}
}
void save(byte[] data, string path)
{
//Create the Directory if it does not exist
if (!Directory.Exists(Path.GetDirectoryName(path)))
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
}
try
{
File.WriteAllBytes(path, data);
Debug.Log("Saved Data to: " + path.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To Save Data to: " + path.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
}
Load:
IEnumerable LoadObject(string path)
{
AssetBundleCreateRequest bundle = AssetBundle.LoadFromFileAsync(path);
yield return bundle;
AssetBundle myLoadedAssetBundle = bundle.assetBundle;
if (myLoadedAssetBundle == null)
{
Debug.Log("Failed to load AssetBundle!");
yield break;
}
AssetBundleRequest request = myLoadedAssetBundle.LoadAssetAsync<GameObject>("boat");
yield return request;
GameObject obj = request.asset as GameObject;
obj.transform.position = new Vector3(0.08f, -2.345f, 297.54f);
obj.transform.Rotate(350.41f, 400f, 20f);
obj.transform.localScale = new Vector3(1.0518f, 0.998f, 1.1793f);
Instantiate(obj);
myLoadedAssetBundle.Unload(false);
}
Right now, it seems UnityWebRequest.GetAssetBundledownload asset to RAM and load. Is there anyway to download to hard disk to load?
This is not really complicated. Handle it like a normal file you would download from the internet but save it with the ".unity3d" extension.
1.Download the AssetBundle as a normal file by making a request with UnityWebRequest.
UnityWebRequest www = UnityWebRequest.Get(url);
yield return www.Send();
2.Retrieve the byte array data with DownloadHandler.data then save it to Application.persistentDataPath/yourfolder/filename.unity3d. Make sure that the extension is ".unity3d".
File.WriteAllBytes(handle.data, data);
That's it.
3.To load the data, use AssetBundle.LoadFromFile or AssetBundle.LoadFromFileAsync:
AssetBundleCreateRequest bundle = AssetBundle.LoadFromFileAsync(path);
If still confused, here is what the thing should look like. You may need to make some modification:
Download and Save:
IEnumerator downloadAsset()
{
string url = "http://url.net/YourAsset.unity3d";
UnityWebRequest www = UnityWebRequest.Get(url);
DownloadHandler handle = www.downloadHandler;
//Send Request and wait
yield return www.Send();
if (www.isError)
{
UnityEngine.Debug.Log("Error while Downloading Data: " + www.error);
}
else
{
UnityEngine.Debug.Log("Success");
//handle.data
//Construct path to save it
string dataFileName = "WaterVehicles";
string tempPath = Path.Combine(Application.persistentDataPath, "AssetData");
tempPath = Path.Combine(tempPath, dataFileName + ".unity3d");
//Save
save(handle.data, tempPath);
}
}
void save(byte[] data, string path)
{
//Create the Directory if it does not exist
if (!Directory.Exists(Path.GetDirectoryName(path)))
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
}
try
{
File.WriteAllBytes(path, data);
Debug.Log("Saved Data to: " + path.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To Save Data to: " + path.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
}
Load:
IEnumerable LoadObject(string path)
{
AssetBundleCreateRequest bundle = AssetBundle.LoadFromFileAsync(path);
yield return bundle;
AssetBundle myLoadedAssetBundle = bundle.assetBundle;
if (myLoadedAssetBundle == null)
{
Debug.Log("Failed to load AssetBundle!");
yield break;
}
AssetBundleRequest request = myLoadedAssetBundle.LoadAssetAsync<GameObject>("boat");
yield return request;
GameObject obj = request.asset as GameObject;
obj.transform.position = new Vector3(0.08f, -2.345f, 297.54f);
obj.transform.Rotate(350.41f, 400f, 20f);
obj.transform.localScale = new Vector3(1.0518f, 0.998f, 1.1793f);
Instantiate(obj);
myLoadedAssetBundle.Unload(false);
}
So I am using the streaming assets folder to hold some information that I need to run my program. Here is how I am determining the filepath to use:
// Location of the top part of the query
public string fileLocation_queryTop = "/Bro/bro_Headers_TOP.json";
// We are on android
if(Application.platform == RuntimePlatform.Android)
{
assetPath = "jar:file://" + Application.dataPath + "!/assets";
}
// We are on iPhone
else if(Application.platform == RuntimePlatform.IPhonePlayer)
{
assetPath = Application.dataPath + "/Raw";
}
// We are on mac or windows
else
{
assetPath = Application.dataPath + "/StreamingAssets";
}
_query_TOP = File.ReadAllText(assetPath + fileLocation_queryTop);
This works fine on Windows, but I am trying to build for Android today.
Here is error that I am getting
I got the info on what path to use from the Unity docs here
I guess what you are looking for is the Application.streamingAssetsPath. You can find more information about it here.
Since you are on Android, you will have to use the WWW class from Unity to retrieve your files.
EDIT:
Following this link you simply have to adjust the file name and store the result in your _query_TOP variable.
private IEnumerator LoadFile()
{
string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "file.txt");
if(filePath.Contains("://"))
{
WWW www = new WWW(filePath);
yield return www;
if(string.IsNullOrEmpty(www.error))
{
_query_TOP = www.text;
}
}
else
{
_query_TOP = System.IO.File.ReadAllText(filePath);
}
}
I have tried all this links bellow:
Not getting image from Persistant path in Android using unity3d
https://developer.vuforia.com/forum/unity-3-extension-technical-discussion/capture-screen-problem-androidhelp
http://answers.unity3d.com/questions/731509/applicationcapturescreenshot-doesnt-save-anything.html
I need to set the path for saving the pictures with an application for Android and IOS with UNITY
http://answers.unity3d.com/questions/200173/android-how-to-refresh-the-gallery-.html#answer-893069
Every time i build an apk, install it on Android device, nothing happend.
Log doesn't exists, so i tryed all this links and then go to /DCIM/Camera/ to see if is it saved, no, nothing...
On iOS i did that, and work perfectly.
Here is some code where i stuck... or the things on Android wont work...
I don't know why no error appear or some file strange in folder
void saveImage()
{
#if UNITY_ANDROID
string theFileName = "Screenshot_" + System.DateTime.Now.ToString("MM_dd_yyyy") +"_"+ System.DateTime.Now.ToString("hh_mm_ss") +".png";
// Many different test, trying to discovery witch will work...
Application.CaptureScreenshot( Application.dataPath + "_" + theFileName );
Application.CaptureScreenshot( "../../../../DCIM/Camera/pathroot_" + theFileName );
Application.CaptureScreenshot( "/storage/emulated/0/DCIM/Camera/" + theFileName );
Application.CaptureScreenshot( "file:///storage/emulated/0/DCIM/Camera/" + theFileName );
StartCoroutine(TakeScreenshot()); // Different test
#endif
#if UNITY_IPHONE
// This work... so, does not need to be here...
#endif
}
This is the method that "Coroutine" calls ( copy from one of those links above ):
private IEnumerator TakeScreenshot()
{
yield return new WaitForEndOfFrame();
//INITIAL SETUP
string myFilename = "Screenshot_" + System.DateTime.Now.ToString("MM_dd_yyyy") +"_"+ System.DateTime.Now.ToString("hh_mm_ss") +".png";
string myDefaultLocation = Application.dataPath + "/" + myFilename;
//EXAMPLE OF DIRECTLY ACCESSING THE Camera FOLDER OF THE GALLERY
//string myFolderLocation = "/storage/emulated/0/DCIM/Camera/";
//EXAMPLE OF BACKING INTO THE Camera FOLDER OF THE GALLERY
//string myFolderLocation = Application.persistentDataPath + "/../../../../DCIM/Camera/";
//EXAMPLE OF DIRECTLY ACCESSING A CUSTOM FOLDER OF THE GALLERY
string myFolderLocation = "/storage/emulated/0/DCIM/Camera/";
string myScreenshotLocation = myFolderLocation + myFilename;
//ENSURE THAT FOLDER LOCATION EXISTS
if(!System.IO.Directory.Exists(myFolderLocation)){
System.IO.Directory.CreateDirectory(myFolderLocation);
}
//TAKE THE SCREENSHOT AND AUTOMATICALLY SAVE IT TO THE DEFAULT LOCATION.
Application.CaptureScreenshot(myFilename);
//MOVE THE SCREENSHOT WHERE WE WANT IT TO BE STORED
System.IO.File.Move(myDefaultLocation, myScreenshotLocation);
//REFRESHING THE ANDROID PHONE PHOTO GALLERY IS BEGUN
AndroidJavaClass classPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject objActivity = classPlayer.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaClass classUri = new AndroidJavaClass("android.net.Uri");
AndroidJavaObject objIntent = new AndroidJavaObject("android.content.Intent", new object[2]{"android.intent.action.MEDIA_MOUNTED", classUri.CallStatic<AndroidJavaObject>("parse", "file://" + myScreenshotLocation)});
objActivity.Call ("sendBroadcast", objIntent);
//REFRESHING THE ANDROID PHONE PHOTO GALLERY IS COMPLETE
//AUTO LAUNCH/VIEW THE SCREENSHOT IN THE PHOTO GALLERY
Application.OpenURL(myScreenshotLocation);
//AFTERWARDS IF YOU MANUALLY GO TO YOUR PHOTO GALLERY,
//YOU WILL SEE THE FOLDER WE CREATED CALLED "myFolder"
}
Try This: (Tested & Works):
Application.CaptureScreenshot ("screenshot.png");
store screenshot at:
Application.persistentDataPath, "screenshot.png" i.e data/data/package_name/files
void captureScreenshot(string result){
if (result == "true") {
StartCoroutine(CaptureScreen());
}
}
void OnGUI(){
if (GUI.Button (new Rect (20, 70, 100, 45), "Click"))
captureScreenshot ("true");
}
public IEnumerator CaptureScreen()
{
// Wait for screen rendering to complete
yield return new WaitForEndOfFrame();
Application.CaptureScreenshot ("screenshot.png");
string Origin_Path = System.IO.Path.Combine (Application.persistentDataPath, "screenshot.png");
Debug.Log ("Origin_Path save is " + Origin_Path);
// This is the path of my folder.
string Path = "/mnt/sdcard/" + "screenshot.png";
Debug.Log ("Path save is " + Path);
if (System.IO.File.Exists (Origin_Path)) {
System.IO.File.Move (Origin_Path, Path);
Debug.Log ("Path_move save is " + Path);
}
jo.Call<bool> ("screenshotHandler", "screenshot.png");
}
If you want to store in gallery without Move again then you can use:
Application.CaptureScreenshot ("../../../../DCIM/screenshot.png");
If Error: System.IO.File.Exists (Origin_Path)
//returns FALSE even though file exists at Origin_Path.
Please try this:
public IEnumerator CaptureScreen()
{
Application.CaptureScreenshot ("../../../../DCIM/"+fileName);
Debug.Log ("Sanky: Screen Captured");
while (!File.Exists (filePath)) {
Debug.Log ("Sanky: File exist at location"+filePath);
yield return 0;
}
/////// do whatever you want
}