Read and Write file on streamingAssetsPath

后端 未结 2 984
谎友^
谎友^ 2020-11-27 08:56

This is how i read my textfile in android.

#if UNITY_ANDROID
string full_path = string.Format("{0}/{1}",Application.streamingAssetsPath, path_with_e         


        
2条回答
  •  温柔的废话
    2020-11-27 09:25

    Now my problem is that i don't know how to write the file on mobile cause I do it like this on the standalone

    You can't save to this location. Application.streamingAssetsPath is read-only. It doesn't matter if it works on the Editor or not. It is read only and cannot be used to load data.

    Reading data from the 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);
    }
    

    Usage:

    Let's load your "datacenter.json" file from your screenshot:

    void Start()
    {
        StartCoroutine(loadStreamingAsset("datacenter.json"));
    }
    


    Saving Data:

    The path to save a data that works on all platform is Application.persistentDataPath. Make sure to create a folder inside that path before saving data to it. The StreamReader in your question can be used to read or write to this path.

    Saving to the Application.persistentDataPath path:

    Use File.WriteAllBytes

    Reading from the Application.persistentDataPath path

    Use File.ReadAllBytes.

    See this post for a complete example of how to save data in Unity.

提交回复
热议问题