read
You can write data in a stream form. Can also use formatted string similar with C
or C++
.
Open several files for writing like this below. If the file exists, it will be overwritten.
private List<StreamWriter> _recordFile;
// Use this for initialization
void Start()
{
_recordFile = new List<StreamWriter>();
_recordFile.Add(File.CreateText("PlayerRecord" + Random.value));
_recordFile.Add(File.CreateText("CameraRecord" + Random.value));
}
Write data like this:
// Record fire information [10/23/2016 Han]
dataRecorder.playerFile.Write(Time.time + "\tPlayer fire" + "\tusing weapon:\t" + weapons[weaponID] + "\n");
You can let some game object in the scene to handle all file staff. I put _recordFile
into a script named GameDataRecorder
. And hang it to a game object in the scene named GameDataRecorder
. Finally, open some interfaces to let other script to use the file stream like this:
public StreamWriter playerFile // open the interface
{
get
{
return _recordFile[0];
}
}
public StreamWriter cameraFile
{
get
{
return _recordFile[1];
}
}
In other script that wants to use the file to write can code like this:
private GameDataRecorder dataRecorder; // the script manages all data files
void Start()
{
// Get the game data record file from game manager [10/23/2016 Han]
dataRecorder = GameObject.FindWithTag(Tags.gameController).GetComponent<GameDataRecorder>();
Debug.Assert(dataRecorder);
}
And write data like this:
// Record changing weapon information [10/23/2016 Han]
dataRecorder.playerFile.Write("\tto:\t" + weapons[weaponID] + "\n");
At last, don’t forget to close the file before application quit.
void OnApplicationQuit()
{
for (int i = 0; i < _recordFile.Count; i++)
{
_recordFile[i].Close();
}
}