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);
}
}
Related
I need to copy a bunch of files from an Android phone to the PC.
It doesn't work the normal way, the PC is super slow and crashes all the time for some reason.
I want to copy it file by file.
My problem is that if I use Directory.GetFiles("Path") or DirectoryInfo.GetFiles("Path") it does add the persistant Datapath to the path for some reason and I get this error message:
DirectoryNotFoundException: Could not find a part of the path 'D:\GameDev\CopyProgram\Dieser PC\HTC One M9\Interner gemeinsamer Speicher'.
The actual path is only "Dieser PC\HTC One M9\Interner gemeinsamer Speicher", is there any way to do that?
//there is an input field where you can enter the paths
(copy it from the explorer)
[SerializeField]
private string copyFrom = "Dieser PC\HTC One M9\Interner gemeinsamer Speicher";
[SerializeField]
private string copyTo = "C:\Users\Nutzer\Desktop\Neuer Ordner";
private bool running = false;
public void Copy()
{
if(running == true)
{
return;
}
running = true;
//Start
//Get all items from folder
DirectoryInfo d = new DirectoryInfo(copyFrom);
FileInfo[] Files = d.GetFiles();
foreach (FileInfo file in Files)
{
string currentFile = file.DirectoryName + "/" + file.Name;
string copyFile = copyTo + "/" + file.Name;
try
{
if (file == null)
continue;
File.Copy(currentFile, copyFile, true);
}
catch (Exception)
{
throw;
}
}
//End
running = false;
}
I searched through the internet and could not find a solution, please help!
Thanks!
This question already has answers here:
Copy files from Resources/StreamingAssets to Application.persistentDataPath upon installation
(2 answers)
Closed 4 years ago.
So, I'm developing Visual Novel in unity. The application is running smoothly in the pc but now I want it to run in android but the contents in my .txt file is not showing in screen. I assume that the error is that the text file in StreamingAssets folder couldn't be loaded and I don't know why. Here's my code:
void Start () {
path = "jar:file://" + Application.dataPath + "!/assets/StreamingAssets/Dialogue0.txt";
lines = new List<DialogueLine>();
Example();
}
IEnumerator Example()
{
if (path.Contains("://"))
{
var www = new WWW(path);
yield return www;
if (!string.IsNullOrEmpty(www.error))
{
Debug.LogError("Can't read");
}
LoadDialogue(www.text);
}
else
LoadDialogue(path);
}
void LoadDialogue(string filename)
{
string line;
StreamReader r = new StreamReader(filename);
using (r)
{
do
{
line = r.ReadLine();
if (line != null)
{
string[] lineData = line.Split('|');
if (lineData[0] == "Player")
{
DialogueLine lineEntry = new DialogueLine(lineData[0], "", 0, 0, "");
lineEntry.options = new string[lineData.Length - 1];
for (int i = 1; i < lineData.Length; i++)
{
lineEntry.options[i - 1] = lineData[i];
}
lines.Add(lineEntry);
}
else
{
DialogueLine lineEntry = new DialogueLine(lineData[0], lineData[1], int.Parse(lineData[2]), int.Parse(lineData[3]), lineData[4]);
lines.Add(lineEntry);
}
}
}
while (line != null);
r.Close();
}
}
Path of my .txt file
Contents of my .txt file
Just serialize your file to Appliction.persistentDataPath + filename and then read easly from it .It will save file in Windows(AppData/LocalLow/InYourUnityProject) in android (under company name folder)
A few moments ago I posted a question because I wasn't able to download a file using WWW() but now I've come to a new problem:
The file that has to be downloaded is ~127mb in size. When I check the file that has been downloaded it shows 55mb. (Which explains why the file isn't able to be opened).
The code I'm using to download the file:
IEnumerator WaitForGame(){
WWW www = new WWW("https://www.dropbox.com/sh/aayo9iud7t98hgb/AACDqSST_-rT2jIfxq1Zc2SXa?dl=1");
Debug.Log ("Downloading");
yield return www;
byte[] yourBytes = www.bytes;
System.IO.File.WriteAllBytes(FullPath, yourBytes);
Debug.Log ("Done downloading!");
}
void UpdateGame(){
string path = Application.dataPath;
if (Application.platform == RuntimePlatform.OSXPlayer) {
path += "/../../";
}
else if (Application.platform == RuntimePlatform.WindowsPlayer) {
path += "/../";
}
if (System.IO.File.Exists (path+"/Apo_Alpha.app")) {
Debug.Log ("File exists!");
System.IO.File.Delete (path+"/Apo_Alpha.app");
}
FullPath = path + "/Apo_Alpha.app";
StartCoroutine (WaitForGame ());
}
I have no clue to what the problem can be, and it would be great if someone could help me out with this one.
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
}
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?