System.IO

Can someone explain me with a simple example script (just write and read a text file containing “hello world”) how to read and write a file? I think it works with System.IO but i feel lost.

I’m not sure about writing to a file, but you can read from a file in your project using TextAsset. May not be exactly what you’re looking for, but it’s an easy way to get text in from a file.

Untested in Unity…

import System.IO;
import System;
import System.Text;

function Start() {
	filewrite("test.txt", "Hellow World!");
	fileread("test.txt");
}
	

function fileread (filename : String) { 
	try { 
		var sr = new StreamReader( Application.dataPath+"/"+filename); 
 
		var line : String = sr.ReadLine();
		
		print(line);
		
		sr.Close();
		sr = null;

		} 
		catch (e) { 
			Debug.Log("internal error!");
			return null;
		}
}

function filewrite (filename : String, text : String) { 
	try { 
		var sw = new StreamWriter( Application.dataPath+"/"+filename); 
 
		sw.WriteLine(text);
		
		sw.Close();
		sw = null;

		} 
		catch (e) { 
			Debug.Log("internal error!");
			return null;
		}
}

works - thanks for the fast reply!

Notice that you do not have file system access in webplayers for security restrictions (similar to java applets). If you want to store data between game sessions no matter if you’re on stand-alone, webplayer or iPhone, use PlayerPrefs: Unity - Scripting API: PlayerPrefs