适用情况:pico vr(安卓)读取配置文件中的url信息,且配置文件可在程序外修改。
- 判断(Application.persistentDataPath + “Data.txt”)是否存在?
- 通过以上存不存在,读写(Application.persistentDataPath + “Data.txt”)文件。
配置文件可以在首次运行后在Android/data/包名中找到,可以在程序外更改。
using LitJson;
using System.IO;
using UnityEngine;
public class ReadJsonDataManager : MonoBehaviour
{
public class UrlInfo
{
public string FlowUrl;
public string EventUrl;
public string ScoreUrl;
}
public static ReadJsonDataManager _inStance;
private const string scene1JsonPathName = "Data.json";
private void Awake()
{
_inStance = this;
}
/// <summary>
/// 此方法非原创,读取StreamingAssets文件夹文件
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string getTextForStreamingAssets(string path)
{
string localPath = "";
if (Application.platform == RuntimePlatform.Android)
{
localPath = Application.streamingAssetsPath + "/" + path;
}
else
{
localPath = "file:///" + Application.streamingAssetsPath + "/" + path;
}
WWW t_WWW = new WWW(localPath); //格式必须是"ANSI",不能是"UTF-8"
if (t_WWW.error != null)
{
Debug.LogError("error : " + localPath);
return ""; //读取文件出错
}
while (!t_WWW.isDone)
{
}
Debug.Log("t_WWW.text= " + t_WWW.text);
return t_WWW.text;
}
/// <summary>
/// 配置文件存取
/// </summary>
/// <returns></returns>
public static string getTextFromApplicationPersistentDataPath()
{
string text = "";
//判断persistentDataPath是否存在
if (!File.Exists(Application.persistentDataPath + "Data.txt"))
{
//从streamingAssetsPath读取原始信息
text = getTextForStreamingAssets(scene1JsonPathName);
//将原始信息写入persistentDataPath
StreamWriter st = File.CreateText(Application.persistentDataPath + "Data.txt");
st.Write(text);
st.Close();
}
//读取persistentDataPath信息
text = File.ReadAllText(Application.persistentDataPath + "Data.txt");
return text;
}
/// <summary>
/// return 配置文件信息,json结构
/// </summary>
/// <returns></returns>
public UrlInfo ReadJsonData()
{
string text = getTextFromApplicationPersistentDataPath();
UrlInfo jsonData = JsonMapper.ToObject<UrlInfo>(text);
if (jsonData != null)
{
print(jsonData.FlowUrl);
print(jsonData.EventUrl);
print(jsonData.ScoreUrl);
return jsonData;
}
else
{
Debug.Log("jsonData为空");
return null;
}
}
}