这就是我在android中读取文本文件的方式。
#if UNITY_ANDROID
string full_path = string.Format("{0}/{1}",Application.streamingAssetsPath, path_with_extention_under_streaming_assets_folder);
// Android only use WWW to read file
WWW reader = new WWW(full_path);
while (!reader.isDone){}
json = reader.text;
// PK Debug 2017.12.11
Debug.Log(json);
#endif
这就是我从pc读取我的文本文件的方式。
#if UNITY_STANDALONE
string full_path = string.Format("{0}/{1}", Application.streamingAssetsPath, path_with_extention_under_streaming_assets_folder);
StreamReader reader = new StreamReader(full_path);
json = reader.ReadToEnd().Trim();
reader.Close();
#endif
现在我的问题是我不知道如何在移动设备上写文件,因为我在单机上是这样做的
#if UNITY_STANDALONE
StreamWriter writer = new StreamWriter(path, false);
writer.WriteLine(json);
writer.Close();
#endif
帮助任何人
更新的问题
这是json文件,它位于我需要获取的streamingasset文件夹中
发布于 2017-12-14 07:54:06
现在我的问题是,我不知道如何在移动设备上写文件,因为我在单机上是这样做的
无法保存到此位置的。Application.streamingAssetsPath
是只读的。它是否能在编辑器上工作并不重要。它是只读的,不能用于加载data。
从StreamingAssets读取数据的
IEnumerator loadStreamingAsset(string fileName)
{
string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, fileName);
string result;
if (filePath.Contains("://") || filePath.Contains(":///"))
{
WWW www = new WWW(filePath);
yield return www;
result = www.text;
}
else
{
result = System.IO.File.ReadAllText(filePath);
}
Debug.Log("Loaded file: " + result);
}
用法
让我们从你的截图中加载你的"datacenter.json“文件:
void Start()
{
StartCoroutine(loadStreamingAsset("datacenter.json"));
}
保存数据
保存可在所有平台上运行的数据的路径为Application.persistentDataPath
。在将数据保存到该路径中之前,请确保在该路径中创建一个文件夹。您问题中的StreamReader
可用于读取或写入此路径。
保存到Application.persistentDataPath
路径:
使用File.WriteAllBytes
从Application.persistentDataPath
路径读取
使用File.ReadAllBytes
。
有关如何在中保存数据的完整示例,请参阅Unity post。
发布于 2017-12-14 07:54:49
这是我在没有WWW
类(适用于Android和iOS)的情况下做到这一点的方法,希望它有用。
public void WriteDataToFile(string jsonString)
{
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
File.WriteAllText(filePath, jsonString);
}
else
{
File.WriteAllText(filePath, jsonString);
}
}
https://stackoverflow.com/questions/47804594
复制