Unity读取Android平台文件

在Android平台上读取文件, StreamingAssets文件夹中的文件,Unity生成apk在安装时会自动放在对应平台的路径下,StreamingAssets 文件夹下的文件在 


移动平台上只能读取,不能写入,移动平台上另一个读写路径 (沙盒)Application.persistentDataPath, 该目录在PC平台、移动平台都是 可读可写


using UnityEngine;
using System.Collections;
using System.IO;


public class Read : MonoBehaviour {


    private string path = "";
    string content = "";
// Use this for initialization
void Start () {


        // 无子路径传 参 "" 
        path = <span style="font-family: Arial, Helvetica, sans-serif;">GetStreamingAssetsPath("");</span>
    }
    // 返回本地 StreamAssetsPath 路径, filePath 为 读写文件的子路径可有可无
    public string GetStreamingAssetsPath(string filePath)
    {
#if UNITY_ANDROID
        //下面两个方法得到的路径相同根据自己的喜好选取
        //return "jar:file:///" + Application.dataPath + "!/assets/" + filePath;
        return Application.streamingAssetsPath + "/" + filePath;
#elif UNITY_IPHONE
        //return Application.dataPath + "/Raw/";
        return "file://" + Application.streamingAssetsPath + "/" + filePath;
#elif UNITY_STANDALONE_WIN || UNITY_EDITOR
        //return Application.dataPath + "/StreamingAssets/";
        return "file:///" + Application.streamingAssetsPath + "/" + filePath;
#else
        return String.Format("{0}/{1}", Application.streamingAssetsPath, filePath);
#endif
    }


    // 根据不同平台获取资源路径,移动平台为沙盒路径, 放在 StreamingAssets 下的文件不在此处
    // 热更新下载文件可以写入到沙盒目录下,游戏中一些需要保存的数据也可以以文件形式写入到改目录下
    // Application.persistentDataPath
    public string GetPersistentDataPath
    {
        get
        {
            //不同平台下 Persistent 的路径是不同的,这里需要注意一下。
#if UNITY_ANDROID
            return "file://" + Application.persistentDataPath + "/";
#elif UNITY_IPHONE
            return "file://" + Application.persistentDataPath + "/";
#elif UNITY_STANDALONE_WIN || UNITY_EDITOR
            return "file:///" + Application.persistentDataPath + "/";
#else
<span style="white-space:pre"> </span>return string.Empty;
#endif
        }
    }

    void OnGUI()
    {
        if (GUI.Button(new Rect(50, 50, 200, 50), "Read"))
        {
            //读取文件
            StartCoroutine(ReadTxt(path, "ABC.txt"));
        }

        if (GUI.Button(new Rect(50, 300, 200, 50), "Clear"))
        {//清空数据
            content = "";
        }

        GUI.Label(new Rect( 50, 500, 300, 80), "path   :  " + path);
        GUI.Label(new Rect(50, 600, 300, 80), "content   :  " + content);
    }

    //项目中的文件在安装到Android平台上后,路径被封装了起来,无法使用IO获取到路径
    //需要使用WWW 去读取存放在工程中的文件
    IEnumerator ReadTxt(string pat, string txtName)
    { 
        string sss = pat + "/" + txtName; //路径 + 需要读取的文件名
        WWW www = new WWW( sss);
        yield return www;
        if (www.isDone)
        {
            content = www.text;
        }
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值