How to load Asset bundle scene in unity 4 - unity3d

I have made asset bundle of a scene like this
[MenuItem("MFKJ/BuildSceneAsset")]
static void myBuild() {
string[] levels = { "Assets/Scene/Scene2.unity" };
string v = BuildPipeline.BuildStreamedSceneAssetBundle(levels, "Assets/AssetBundles/Streamed-Level2.unity3d", BuildTarget.StandaloneWindows);
Debug.Log(v);
//"Streamed-Level1.unity3d"
//BuildPipeline.BuildStreamedSceneAssetBundle(levels, "Streamed-Level1.unity3d", BuildTarget.StandaloneWindows64);
}
This has made a .unity3d assetbundle file in specified folder.
Now on run time i am loading the scene from asset bundle form another scene using this code.
public string url;
// Use this for initialization
void Start () {
url = "file://" + Application.dataPath + "/AssetBundles/Streamed-Level2.unity3d";
Debug.Log("scene load url : " + url);
StartCoroutine(LoadSceneBundle());
}
// Update is called once per frame
void Update () {
}
public IEnumerator LoadSceneBundle() {
using (WWW www = WWW.LoadFromCacheOrDownload(url,1)){
yield return www;
if (www.error != null) {
throw new Exception("WWW donwload had an error : " + url + " " + www.error);
//Debug.Log("");
}
AssetBundle ab = www.assetBundle;
Debug.Log(www.assetBundle.mainAsset);
//GameObject gm = ab.mainAsset as GameObject;
//Debug.Log("Scene2PassValue : " + gm.name);
//Instantiate(gm);
//ab.LoadAll(typeof(GameObject));
ab.LoadAll();
ab.Unload(false);
}
}
but unfortunately this is not loading the streamed scene or any asset of streamed scene from asset bundle. what i am missing?

Related

Save and Load file in HoloLens using Unity editer

I'm trying to Save and Load Vector3 Coordinates in HoloLens App the program works on my laptop using unity but it will not save or load a file in the HoloLens.
Here is the program I am using to create the path for saving and loading. Any help would be appreciated.
public GameData Load()
{
string fullPath = Path.Combine(dataDirPath, dataFileName);
GameData loadedData = null;
if (File.Exists(fullPath))
{
try
{
string dataToLoad = "";
using (FileStream stream = new FileStream(fullPath, FileMode.Open))
{
using (StreamReader reader = new StreamReader(stream))
{
dataToLoad = reader.ReadToEnd();
}
}
loadedData = JsonUtility.FromJson<GameData>(dataToLoad);
}
catch (Exception e)
{
UnityEngine.Debug.LogError("Error occured when trying to load data from filr: " + fullPath + "\n" + e);
}
}
return loadedData;
}
public void Save (GameData data)
{
string fullPath = Path.Combine(dataDirPath, dataFileName);
try
{
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
string dataToStore = JsonUtility.ToJson(data, true);
using (FileStream stream = new FileStream(fullPath, FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(dataToStore);
}
}
}
catch (Exception e)
{
UnityEngine.Debug.LogError("Error occured when trying to save data to file: " + fullPath + "\n" + e);
}
}
}
If I understand this correctly, you're debugging remotely. To clarify, your application cannot access files on HoloLens until you deploy it to HoloLens. And for how to access files on HoloLens, you can refer Create, write, and read a file - UWP applications | Microsoft Learn and Working with File on Hololens 2 (UWP to .NET).

Downloading images and save to device

I having some issues here with UnityWebRequest.
I tried to download and save the jpeg, but it seem that the download is a success but it does not save it, and does not show me Log from "saveToFile" function.
Did I did something wrong?
Here are my code.
public string folderPath;
void Start()
{
folderPath = Application.persistentDataPath + "/" + FileFolderName;
}
IEnumerator DownloadingImage(Uri url2)
{
Debug.Log("Start Downloading Images");
using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(url2))
{
// uwr2.downloadHandler = new DownloadHandlerBuffer();
yield return uwr.SendWebRequest();
if (uwr.isNetworkError || uwr.isHttpError)
{
Debug.Log(uwr.error);
}
else
{
Debug.Log("Success");
Texture myTexture = DownloadHandlerTexture.GetContent(uwr);
byte[] results = uwr.downloadHandler.data;
saveImage(folderPath, results);
}
}
}
void saveImage(string path, byte[] imageBytes)
{
//Create Directory if it does not exist
if (!Directory.Exists(Path.GetDirectoryName(path)))
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
Debug.Log("Creating now");
}
else
{
Debug.Log(path + " does exist");
}
try
{
File.WriteAllBytes(path, imageBytes);
Debug.Log("Saved Data to: " + path.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To Save Data to: " + path.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
}
You have wrong file name so give filename with extension,
If you don't give extension, 'Directory.Exists' doesn't know whether file or directory.
or you could separate parameters such as rootDirPath and filename.
IEnumerator DownloadingImage(Uri url2)
{
Debug.Log("Start Downloading Images");
using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(url2))
{
// uwr2.downloadHandler = new DownloadHandlerBuffer();
yield return uwr.SendWebRequest();
if (uwr.isNetworkError || uwr.isHttpError)
{
Debug.Log(uwr.error);
}
else
{
Debug.Log("Success");
Texture myTexture = DownloadHandlerTexture.GetContent(uwr);
byte[] results = uwr.downloadHandler.data;
string filename = gameObject.name+".dat";
// saveImage(folderPath, results); // Not a folder path
saveImage(folderPath+"/"+filename, results); // give filename
}
}
}

How do I upload files from a phone to my Amazon S3 server?

I'm developing a mobile app with Unity and using S3 to store and retrieve assets, I can download asset bundles just fine from the server to the phone, but how do I upload files from the phone to the server?
I used the PostObject function from the AWS Unity SDK, and it works fine if I upload from the computer as I know the directory, but I'm not sure how to get the phone's photo gallery to upload to the s3 server.
This is the PostObject function
public void PostObject(string fileName)
{
ResultText.text = "Retrieving the file";
var stream = new FileStream("file://" + Application.streamingAssetsPath + "/" + fileName,
FileMode.Open, FileAccess.Read, FileShare.Read);
Debug.Log("kek");
ResultText.text += "\nCreating request object";
var request = new PostObjectRequest()
{
Bucket = S3BucketName,
Key = fileName,
InputStream = stream,
CannedACL = S3CannedACL.Private,
Region = _S3Region
};
ResultText.text += "\nMaking HTTP post call";
Client.PostObjectAsync(request, (responseObj) =>
{
if (responseObj.Exception == null)
{
ResultText.text += string.Format("\nobject {0} posted to bucket {1}",
responseObj.Request.Key, responseObj.Request.Bucket);
}
else
{
ResultText.text += "\nException while posting the result object";
ResultText.text += string.Format("\n receieved error {0}",
responseObj.Response.HttpStatusCode.ToString());
}
});
}
And this is where I'm using it to upload the picture taken from the phone to the server
public void TakePicture(int maxSize)
{
NativeCamera.Permission permission = NativeCamera.TakePicture((path) =>
{
Debug.Log("Image path: " + path);
if (path != null)
{
// Create a Texture2D from the captured image
Texture2D imageTexture = NativeCamera.LoadImageAtPath(path, maxSize);
if (imageTexture == null)
{
Debug.Log("Couldn't load texture from " + path);
return;
}
//picturePreview.gameObject.SetActive(true);
//picturePreview.texture = imageTexture;
Texture2D readableTexture = DuplicateTexture(imageTexture);
StartCoroutine(AddImageJob(readableTexture));
//Saves taken photo to the Image Gallery
if (isSaveFiles)
{
NativeGallery.SaveImageToGallery(imageTexture, "AReview", "test");
//Upload to Amazon S3
aws.PostObject(imageTexture.name);
aws.PostObject("test");
}
}
}, maxSize);
Debug.Log("Permission result: " + permission);
}
Any clues?
Thank you.

Unity WebGL - accessing StreamingAssets folder from build uploaded in LMS /Server

I couldn't access the files StreamingAssets folder from WebGL build which is uploaded in LMS server, I kept those files in StreamingAssets folder to update it for future use. Followed the instruction given in unity manual, working fine in editor, but with direct build run and in LMS its not working.
http://docs.unity3d.com/ScriptReference/Application-streamingAssetsPath.html
Posted in forums, they ask to follow the manual, but its not working. Please find the script attached here for more details. Check the coroutine function named ' userDetailsXmlPath ' which called at start of the game.
public string filePath = Application.streamingAssetsPath + "/UserDetails.xml";
public string result = "";
IEnumerator userDetailsXmlPath()
{
print (filePath);
if (filePath.Contains ("://") || filePath.Contains (":///")) {
WWW www = new WWW (filePath);
yield return www;
result = www.text;
print (result);
FetchUserDetails ();
} else {
result = File.ReadAllText (filePath);
print (result);
FetchUserDetails ();
}
}
public void FetchUserDetails()
{
XmlDocument userXml1 = new XmlDocument ();
// userXml1.Load(Application.streamingAssetsPath + "/UserDetails.xml");
// userXml1.Load(Application.dataPath + "js/UserDetails 1.xml");
// userXml1.LoadXml(userXml.text);
userXml1.LoadXml(result);
XmlNodeList userList = userXml1.GetElementsByTagName ("user");
foreach(XmlNode userValue in userList)
{
XmlNodeList userContent = userValue.ChildNodes;
objUser = new Dictionary<string, string>();
foreach(XmlNode value in userContent)
{
objUser.Add (value.Name, value.InnerText);
}
userFullDetails.Add (objUser);
userCountInXml = userList.Count;
userId = new string[userList.Count];
questionSetOfUser = new string[userList.Count];
}
AssignUserXmlValuesToArray ();
}
Please guild me to resolve this issue.
Access StreamingAssets path folder using WWW class https://docs.unity3d.com/ScriptReference/Application-streamingAssetsPath.html
public string filePath = Application.streamingAssetsPath + "/UserDetails.xml";
public string result = "";
void Awake ()
{
filePath = Application.streamingAssetsPath + "/UserDetails.xml";
}
void Start ()
{
StartCoroutine(userDetailsXmlPath() );
}
IEnumerator userDetailsXmlPath()
{
print (filePath);
if (filePath.Contains ("://") || filePath.Contains (":///")) {
WWW www = new WWW (filePath);
yield return www;
result = www.text;
print (result);
FetchUserDetails ();
} else {
result = File.ReadAllText (filePath);
print (result);
FetchUserDetails ();
}
}
public void FetchUserDetails()
{
XmlDocument userXml1 = new XmlDocument ();
userXml1.LoadXml(result);
XmlNodeList userList = userXml1.GetElementsByTagName ("user");
foreach(XmlNode userValue in userList)
{
XmlNodeList userContent = userValue.ChildNodes;
objUser = new Dictionary<string, string>();
foreach(XmlNode value in userContent)
{
objUser.Add (value.Name, value.InnerText);
}
userFullDetails.Add (objUser);
userCountInXml = userList.Count;
userId = new string[userList.Count];
questionSetOfUser = new string[userList.Count];
}
AssignUserXmlValuesToArray ();
}

Unity WebGL build with SCORM 1.2 is not working in LMS

I have integrated SCORM 1.2 with my game which produces WebGL output, if we play the WebGL out directly in browser its working fine and not working in LMS. Found that the game play script included in the game causing the issue, when I disable it and upload the build in LMS its loading (can't proceed with game-play, since script is disabled)
In this script I am using GAF function, Xml data fetching from file placed in StreamingAssets folder, not using any WWW class.
SCORM asset pack included in game,
https://www.assetstore.unity3d.com/en/#!/content/53523
Have no idea which function restricting the game from running, could you please have a look on this and send me the feedback.
Error message
Please find the attachment.enter image description here
Access StreamingAssets path folder using WWW class
https://docs.unity3d.com/ScriptReference/Application-streamingAssetsPath.html
public string filePath = Application.streamingAssetsPath + "/UserDetails.xml";
public string result = "";
void Awake ()
{
filePath = Application.streamingAssetsPath + "/UserDetails.xml";
}
void Start ()
{
StartCoroutine(userDetailsXmlPath() );
}
IEnumerator userDetailsXmlPath()
{
print (filePath);
if (filePath.Contains ("://") || filePath.Contains (":///")) {
WWW www = new WWW (filePath);
yield return www;
result = www.text;
print (result);
FetchUserDetails ();
} else {
result = File.ReadAllText (filePath);
print (result);
FetchUserDetails ();
}
}
public void FetchUserDetails()
{
XmlDocument userXml1 = new XmlDocument ();
userXml1.LoadXml(result);
XmlNodeList userList = userXml1.GetElementsByTagName ("user");
foreach(XmlNode userValue in userList)
{
XmlNodeList userContent = userValue.ChildNodes;
objUser = new Dictionary<string, string>();
foreach(XmlNode value in userContent)
{
objUser.Add (value.Name, value.InnerText);
}
userFullDetails.Add (objUser);
userCountInXml = userList.Count;
userId = new string[userList.Count];
questionSetOfUser = new string[userList.Count];
}
AssignUserXmlValuesToArray ();
}