查看: 1452|回复: 0
打印 上一主题 下一主题

[其他] 在Unity中读取和写入文本文件的方法

[复制链接]

2317

主题

54

听众

2万

积分

资深设计师

Rank: 7Rank: 7Rank: 7

纳金币
20645
精华
62

最佳新人 活跃会员 热心会员 灌水之王 突出贡献

跳转到指定楼层
楼主
发表于 2014-11-30 08:09:08 |只看该作者 |倒序浏览

读取和写入文本文件可以用unity自带的类,也可以用C#原生提供的。

1.unity自带的TextAsset:
TextAsset test = (TextAsset)Resources.Load("xxxx");
string temp = test.text;


2,使用C#文件流加载外部文本文件:

(1)先构造一个可以读取和写入的类
using System;
using System.IO;

public class FileReadWriteManager
{
    public void WriteTextFile(string pathAndName,string stringData)
    {
        FileInfo textFile=new FileInfo(pathAndName);
        if(textFile.Exists)
            textFile.Delete();
        StreamWriter writer;
        writer=textFile.CreateText();
        writer.Write(stringData);
        writer.Close();
    }


    public string ReadTextFile(string pathAndName)
    {
        string dataAsString="";
        try{
            StreamReader textReader=File.OpenText(pathAndName);
            dataAsString=textReader.ReadToEnd();
            textReader.Close();
        }
        catch(Exception e)
        {
            Debug.Log("xxxx");
        }

        return dataAsString;
    }
}


(2)在unity中使用调用读文件
using UnityEngine;
using System.Collections;
using System.IO;
public class test : MonoBehaviour {

    string filePath = "";
    string text = "";
    FileReadWriteManager file = new FileReadWriteManager();
       
        void Start () {
        string fileName = "xx.txt";
        filePath = Path.Combine(Application.dataPath,"Resources");
        filePath = Path.Combine(filePath, fileName);
        text = file.ReadTextFile(filePath);
        }

}

(3)在unity中使用,调用写文件
FileReadWriteManager file = new FileReadWriteManager();
filePath=Application.dataPath+Path.DirectorySeparatorChar+fileName;
string  text="Hello";
file.WriteTextFile(filePath,text);


Tips: 使用Path.Combine(Application.dataPath,"Resources");来代替斜杠可以避免很多问题。
[url=]Path[/url].DirectorySeparatorChar 目录分隔符
默认字符用于分隔目录层次。(只读)
This is '\' on Windows and '/' on Mac OS X
Windows用"\",Mac OS用"/"。


分享到: QQ好友和群QQ好友和群 腾讯微博腾讯微博 腾讯朋友腾讯朋友 微信微信
转播转播0 分享淘帖0 收藏收藏0 支持支持0 反对反对0
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

关闭

站长推荐上一条 /1 下一条

手机版|纳金网 ( 闽ICP备08008928号

GMT+8, 2024-5-15 06:16 , Processed in 0.085275 second(s), 31 queries .

Powered by Discuz!-创意设计 X2.5

© 2008-2019 Narkii Inc.

回顶部