Unity在各平臺下讀取StreamingAssets文件夾中的文件(Unity5版本適用)

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();
    }

踩過的坑:

  1. 在移動平臺下,Application.streamingAssetsPath只讀的,不能寫入數據Application.persistentDataPath 可以讀取和寫入數據。
  2. 在PC下,可以用File類API(如File.ReadAllText)讀寫StreamingAssets文件夾中的文件;在IOS和Android平臺下,不能用File類API讀取。
  3. 所有平臺上都可以用www方式異步讀取StreamingAssets文件夾,PC和IOS平臺下,讀取路徑必須加上"file://",而安卓不需要。
  4. 在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");

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章