I do localization in my game, and I write words in different languages into a JSon file. Everything works in Unity Editor, but on android it throws an exception Cannot find file!
public void LoadLocalizedText(string langName)
{
#if UNITY_ANDROID && !UNITY_EDITOR
string path ="jar:file://" + Application.streamingAssetsPath + "/Languages/" + langName + ".json";
#else
string path = Application.streamingAssetsPath + "/Languages/" + langName + ".json";
#endif
if (File.Exists(path))
{
if (File.Exists(path))
{
string dataAsJson;
#if UNITY_ANDROID && !UNITY_EDITOR
WWW reader = new WWW(path);
UnityWebRequest unityWebRequest = new UnityWebRequest(path);
while (!reader.isDone) { }
dataAsJson = reader.text;
#else
dataAsJson = File.ReadAllText(path);
#endif
LocalizationData loadedData = JsonUtility.FromJson<LocalizationData>(dataAsJson);
localizedText = new Dictionary<string, string>();
for (int i = 0; i < loadedData.items.Length; i++)
{
localizedText.Add(loadedData.items[i].key, loadedData.items[i].value);
}
currentLanguage = langName;
isReady = true;
OnLanguageChanged?.Invoke();
}
else
{
throw new Exception("Cannot find file!");
}
}
You dont need to add "jar:file//" on android for streaming assets path. Also, if you on android, you'll not pass your File.Exists(pass) checks. Here is the working exapmple.
Related
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)
How can I replace my new database file to my previous database file?
My previous database is inside the folder :
string filepath = Application.persistentDataPath + "/" + "Martyr.db";
My app code:
string filePath = Application.persistentDataPath + "/" + "Martyr.db";
string disPath;
if (!File.Exists(filePath))
{
disPath = System.IO.Path.Combine(Application.streamingAssetsPath, "Martyr.db");
WWW loadDB;
#if UNITY_ANDROID
{
loadDB = new WWW(disPath);
}
#if UNITY_EDITOR
{
loadDB = new WWW("file://" + Application.streamingAssetsPath + "/Martyr.db");
}
#else
{loadDB=new WWW(dispath);}
#endif
#endif
while (!loadDB.isDone)
{
}
File.WriteAllBytes(filePath, loadDB.bytes);
}
You can simply delete your old Databasefile and write a new one.
string filePath = Application.persistentDataPath + "/" + "Martyr.db";
string disPath;
if (File.Exists(filePath)) {
File.Delete(filePath);
}
disPath = System.IO.Path.Combine(Application.streamingAssetsPath, "Martyr.db");
WWW loadDB;
#if UNITY_ANDROID
{
loadDB = new WWW(disPath);
}
#if UNITY_EDITOR
{
loadDB = new WWW("file://" + Application.streamingAssetsPath + "/Martyr.db");
}
#else
{loadDB=new WWW(dispath);}
#endif
#endif
while (!loadDB.isDone) {
}
File.WriteAllBytes(filePath, loadDB.bytes);
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'm using DotNetZip library to make multi-file zip archive and download it on the fly (no need to wait for download to start). However I can't make it to download instantly. From browser dev console, in network tab I noticed that first zip file is "transferred" and after being fully transferred it starts downloading.
Here is code fragment:
using (var vZipArchive = new ZipFile())
{
if (vFilesTable.Rows.Count > 0)
{
string vPathFormat = null;
string vKeyName = null;
string vPrimKey = null;
string vFileName = null;
vZipArchive.CompressionLevel = CompressionLevel.BestSpeed;
vZipArchive.CompressionMethod = CompressionMethod.Deflate;
vZipArchive.Comment = "Document Archive";
foreach (DataRow vFile in vFilesTable.Rows)
{
if (vKeyFieldName != null && !string.IsNullOrEmpty(vKeyFieldName))
{
vPathFormat = "{0}/";
}
else
{
vPathFormat = "/";
}
if (vFile.Table.Columns.Contains("FileName") && vFile.Table.Columns.Contains("PrimKey"))
{
vPrimKey = vFile["PrimKey"].ToString();
vFileName = vFile["FileName"].ToString();
if (vKeyFieldName != null)
{
vKeyName = vFile[vKeyFieldName].ToString();
}
string vPath = null;
if (vKeyFieldName != null)
{
vPath = string.Format(vKeyFieldName + " " + vPathFormat + "{1}", vKeyName, vFileName);
}
else
{
vPath = string.Format(vPathFormat + vFileName);
}
using (var vFileStream = vUserContext.GetFileStream(vRecordSource.ViewName, new Guid(vPrimKey)))
{
vFileStream.Position = 0;
vZipArchive.AddEntry(vPath, vFileStream);
}
}
else
{
throw new Exception("Select 'FileName' and 'PrimKey' fields in underlying DataSource");
}
} //end loop
pContext.Response.Clear();
pContext.Response.BufferOutput = false;
pContext.Response.ContentType = "application/zip";
pContext.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}.zip\"", vZipName));
vZipArchive.Save(pContext.Response.OutputStream);
}
else
{
return;
}
}
I also tried using ZipOutputStream and SharpCompress.dll library.
So, what I am missing to make it work? Or its impossible?
I want to get window explorer Directory path under mouse cursor.
I tried AutomationElement but it only detect name or process id etc that I dont want. I
also tried SHDocVw.ShellWindows It seems working but I cant define which one is choosen.
here is a source i tried
string GetDropPath(AutomationElement element){
string dir = element.Current.Name;
if (dir.Split('.').Length >= 2) return null;
string desktop = CommonDir["Desktop"];
if (Directory.Exists(desktop + "\\" + dir))
{
dir = desktop + "\\" + dir;
}
else
{
if (CommonDir.ContainsKey(dir))
{
dir = CommonDir[dir];
}
else if (!Directory.Exists(dir))
{
foreach (InternetExplorer item in new SHDocVw.ShellWindows())
{
//uint ppid = 0;
//GetWindowThreadProcessId(item.HWND, out ppid);
if (item.LocationURL.ToString().StartsWith("file:///"))
{
List<int> children = GetAllChildrenWindowHandles(item.HWND, 100);
if (item.HWND == element.Current.NativeWindowHandle || children.Contains(element.Current.NativeWindowHandle))
{
string pth = item.LocationURL.Replace("file:///", "");
if (Directory.Exists(pth + "\\" + dir))
{
dir = pth + "\\" + dir;
}
else
{
dir = pth;
}
break;
}
}
}
}
}
if (Directory.Exists(dir))
{
return dir;
}
else
{
return null;
}
}