void Awake()
{
string path =
#if UNITY_ANDROID && !UNITY_EDITOR
Application.streamingAssetsPath + "/Josn/modelname.json";
#elif UNITY_IPHONE && !UNITY_EDITOR
"file://" + Application.streamingAssetsPath + "/Josn/modelname.json";
#elif UNITY_STANDLONE_WIN||UNITY_EDITOR
"file://" + Application.streamingAssetsPath + "/Josn/modelname.json";
#else
string.Empty;
#endif
StartCoroutine(ReadData(path));
}
IEnumerator ReadData(string path)
{
WWW www = new WWW(path);
yield return www;
while (www.isDone == false)
{
yield return new WaitForEndOfFrame();
}
yield return new WaitForSeconds(0.5f);
string data = www.text;
yield return new WaitForEndOfFrame();
}
踩過的坑:
- 在移動平臺下,Application.streamingAssetsPath是只讀的,不能寫入數據。Application.persistentDataPath 可以讀取和寫入數據。
- 在PC下,可以用File類API(如File.ReadAllText)讀寫StreamingAssets文件夾中的文件;在IOS和Android平臺下,不能用File類API讀取。
- 所有平臺上都可以用www方式異步讀取StreamingAssets文件夾,PC和IOS平臺下,讀取路徑必須加上"file://",而安卓不需要。
- 在IOS和Android下,還能用AssetBundle.LoadFromFile來同步讀取數據。
string path =
#if UNITY_ANDROID
Application.dataPath + "!assets"+ "/";
#else
Application.streamingAssetsPath + "/";
#endif
AssetBundle assetbundle = AssetBundle.LoadFromFile(path +"sprite.unity3d");
Sprite sprite = assetbundle.LoadAsset<Sprite>("test");