آموزش خواندن از فایل در یونیتی / نوشتن در فایل متنی در یونیتی
خواندن و نوشتن فایل در یونیتی
using UnityEngine;
using UnityEditor;
using System.IO;
public class HandleTextFile
{
[MenuItem("Tools/Write file")]
static void WriteString()
{
string path = "Assets/Resources/test.txt";
//Write some text to the test.txt file
StreamWriter writer = new StreamWriter(path, true);
writer.WriteLine("Test");
writer.Close();
//Re-import the file to update the reference in the editor
AssetDatabase.ImportAsset(path);
TextAsset asset = Resources.Load("test");
//Print the text from the file
Debug.Log(asset.text);
}
[MenuItem("Tools/Read file")]
static void ReadString()
{
string path = "Assets/Resources/test.txt";
//Read the text from directly from the test.txt file
StreamReader reader = new StreamReader(path);
Debug.Log(reader.ReadToEnd());
reader.Close();
}
}
مثال دیگر:
public string FileName; // This contains the name of the file. Don't add the ".txt"
// Assign in inspector
private TextAsset asset; // Gets assigned through code. Reads the file.
private StreamWriter writer; // This is the writer that writes to the file
void AppendString(string appendString) {
asset = Resources.Load(FileName + ".txt") as TextAsset;
writer = new StreamWriter("Resources/" + FileName + ".txt"); // Does this work?
writer.WriteLine(appendString);
}