Unity读取PC端文件

来源:互联网 发布:淘宝网耐克运动鞋 编辑:程序博客网 时间:2024/04/19 09:15

将该代码脚本托转到摄像机上,将  ABC.txt文件放在 Assets 下的 StreamingAssets 文件夹内,没有该文件夹自己创建, 

在 编辑状态下和   生成 .exe 在 WinPC上运行无问题

在Android下,使用 IO 是无法使用下面的路径去读取文件的,只能用 WWW 去加载, 注意如果要读取工程中的 文件,一定要放在 StreamingAssets 下, Unity系统会自动将StreamingAssets文件下的文件放到相应平台的路径下,无需代码操作

using UnityEngine;using System.Collections;using System.IO;public class Read : MonoBehaviour {    private string path = "";    string content = "";// Use this for initializationvoid Start () {        //获取本地路径     #if UNITY_IPHONE        path = path = Application.dataPath + "/Raw"; // Iphone路径#elif UNITY_ANDROID        path = "jar:file://" + Application.dataPath + "!/assets/"; // Android路径#elif UNITY_EDITOR        path = Application.dataPath + "/StreamingAssets"; // PC路径#endif   }    void OnGUI()    {        if (GUI.Button(new Rect(50, 50, 200, 50), "Read"))        {            //读取文件            ReadMyTxt(path, "AAA.txt");        }        if (GUI.Button(new Rect(50, 150, 200, 50), "Create"))        {            CreateTxt(path, "AAA.txt", "aaaaaaaaaabbbbbbbbbbcccccccccdddddddddd");        }        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);    }    //读取txt文件,参数1为路径,参数2为文件名(要带后缀)    private void ReadMyTxt(string pat, string txtName)    {        string sss = path + "/" + txtName;        if (!File.Exists(sss)) //如果文件不存在退出        {            content = "!Exists " + sss;            return;        }        try        {            //实例化文件流,参数1 路径,参数2文件操作方式            FileStream file = new FileStream(sss, FileMode.Open);            StreamReader sr = new StreamReader(file);            content = sr.ReadToEnd(); //从文件头读取到文件尾            sr.Close();  //关闭流释放空间            file.Close();         }        catch{}    }    //如果ReadMyTxt(string pat, string txtName)读取失败,尝试使用 ReadTxtBBB    private void ReadTxtBBB(string pat, string txtName)    {        string sss = pat + "//" + txtName;        StreamReader sr = null;        try        {            sr = File.OpenText(sss);        }        catch        {            return;        }        content = sr.ReadToEnd();        sr.Close();        sr.Dispose();    }    //创建文件,参数1 路径,参数2 文件名,参数3 写入信息    private void CreateTxt(string pat, string txtName, string info)    {        string sss = path + "/" + txtName;        try        {            StreamWriter sw;            FileInfo t = new FileInfo(sss);            //如果文件不存在则创建一个            if (!t.Exists)            {                sw = t.CreateText();            }            else            {                sw = t.AppendText();            }            //写入信息            sw.WriteLine(info);            content = "write : " + info;            sw.Close();            sw.Dispose();        }        catch {}    }}


0 0