读取和写入文本文件可以用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用"/"。
|