I’m totally new to coding. I am trying to develop a psychological test based on Reaction Times.
In a script I created a list that during the session gets filled with 7 float numbers. The list is…
public List reactionTimes = new List();
After the session I would like to export the 7 reaction times in a text file on my Mac. So I created another Script, attached to an empty object in Unity, named SaveData. I was trying to experiment on this following some online tutorials but I can’t figure out how it is intended to be done. Even though there is no error reported on the Scripts, nothing seems to happen. This is the code, adding using System.IO.
public class SaveData : MonoBehaviour {
ReactionTime subjectresults;
// Use this for initialization
void Start () {
subjectresults = GetComponent <ReactionTime>();
}
// Update is called once per frame
void Update () {
}
private void SaveToFile()
{
StreamWriter writer = new StreamWriter (@"path");
foreach (float TR in subjectresults.reactionTimes)
{
float output = TR;
writer.WriteLine (output);
writer.Close ();
}
}
You are closing the writer before writing all the lines…
Use the following method instead:
private void SaveToFile()
{
// Convert the floats to strings
string[] lines = new string[subjectresults.reactionTimes.Length];
for( int i = 0 ; i < subjectresults.reactionTimes.Length ; ++i )
lines _= subjectresults.reactionTimes*.ToString();*_
// Write the lines into the file File.WriteAllLines(Application.persistentDataPath + “/reactionTimes.txt”, lines); }
I tried using your method but I still can’t find a way to save this .txt on my desktop (for example).
Actually I can’t find the .txt anywhere on my Mac (unfortunately I don’t have a PC at the moment).
Do you have any idea about what I’m missing?
Hello again @Hellium ,
I still can’t figure out why this file I’m trying to save doesn’t exist apparently anywhere on my mac.
This is my actual code…
The only differences from yours are: reactionTimes.Count instead of “Lenght”, because reactionTimes is a List, and I’ve added System.Environment, because with only Environment it was returning an error.
ReactionTime subjectresults;
// Use this for initialization
void Start () {
subjectresults = GetComponent <ReactionTime>();
}
// Update is called once per frame
void Update () {
}
private void SaveToFile()
{
// Convert the floats to strings
string[] lines = new string[subjectresults.reactionTimes.Count];
for (int i = 0; i < subjectresults.reactionTimes.Count; ++i)
lines _= subjectresults.reactionTimes *.ToString ();*_
* // Write the lines into the file* * string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);* * File.WriteAllLines (path + “/reactionTimes.rtf”, lines);* * }* }