0
\$\begingroup\$

I am writing data to a file every two seconds. I used InvokeRepeating and everything is Ok except that every record is saved 3 times in the file:

void Start(){
    File.WriteAllText(filePath_users, "timestamp" + "," + "id" + "," + "pos" + "," + "rot" + System.Environment.NewLine);
    InvokeRepeating("SaveUsersTracking", 1.0f, 2.0f);
}

void SaveUsersTracking(){
    //save this data every two seconds...
    File.AppendAllText(filePath_users, System.DateTime.Now.ToString() + "," + "U1" + "," + "(-2.7, 1.3, -1.8)" + "," + "(0.2, -0.7, 0.2)" + System.Environment.NewLine);
}

My results look like:

timestamp,id,pos,rot
4/20/2019 8:09:47 PM,U1,(-2.7, 1.3, -1.8),(0.2, -0.7, 0.2)
4/20/2019 8:09:47 PM,U1,(-2.7, 1.3, -1.8),(0.2, -0.7, 0.2)//I don't need this record
4/20/2019 8:09:47 PM,U1,(-2.7, 1.3, -1.8),(0.2, -0.7, 0.2)//I don't need this record
4/20/2019 8:09:49 PM,U1,(-2.7, 1.3, -1.8),(0.2, -0.7, 0.2)
4/20/2019 8:09:49 PM,U1,(-2.7, 1.3, -1.8),(0.2, -0.7, 0.2)//I don't need this record
4/20/2019 8:09:49 PM,U1,(-2.7, 1.3, -1.8),(0.2, -0.7, 0.2)//I don't need this record
4/20/2019 8:09:51 PM,U1,(-2.7, 1.3, -1.8),(0.2, -0.7, 0.2)
4/20/2019 8:09:51 PM,U1,(-2.7, 1.3, -1.8),(0.2, -0.7, 0.2)//I don't need this record
4/20/2019 8:09:51 PM,U1,(-2.7, 1.3, -1.8),(0.2, -0.7, 0.2)//I don't need this record
\$\endgroup\$
  • \$\begingroup\$ Could there be three instances of this MonoBehaviour active in the scene? \$\endgroup\$ – Ed Marty Apr 21 '19 at 16:09
0
\$\begingroup\$

Remove the 2.0f from the end of InvokeRepeating The second argument is a repeat rate so it is saving it 3 times (the executed plus the 2 repeats).

void Start(){
    File.WriteAllText(filePath_users, "timestamp" + "," + "id" + "," + "pos" + "," + "rot" + System.Environment.NewLine);
    InvokeRepeating("SaveUsersTracking", 1.0f);
}

void SaveUsersTracking(){
    //save this data every two seconds...
    File.AppendAllText(filePath_users, System.DateTime.Now.ToString() + "," + "U1" + "," + "(-2.7, 1.3, -1.8)" + "," + "(0.2, -0.7, 0.2)" + System.Environment.NewLine);
}
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ A good answer is one which doesn't just fix the mistake but also tells people how to avoid that mistake in the future by explaining them what they misunderstood. Can you explain why this solves the problem? \$\endgroup\$ – Philipp Apr 25 '19 at 17:07
  • \$\begingroup\$ edited answer to better explain what the mistake was. \$\endgroup\$ – Justin Markwell Apr 25 '19 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.