我正在使用streamwriter在csv文件中播放時保存我的遊戲數據。爲了做到這一點,我在啓動函數中初始化了我的Streamwriter,併爲我的數據的頭部寫了第一行。然後在更新函數中,我在該文件中寫入變化的遊戲變量。我的問題是以下幾點:如果if語句不再正確後如何正確關閉streamwriter?
這工作正常,我可以看到我的csv文件與數據時,我單擊手動停止在遊戲中。但是,當我等到myTimer(遊戲的持續時間爲< = 0)並且GUI正在重新加載時,我只是得到一個空的csv文件。 我認爲這個問題是有關的事實,我沒有正確關閉我的StreamWriter ...這裏是我的代碼:
// Use this for initialization
public void Start()
{
//create file (txt or csv) with streamwriter which has the name of the Subject and Information which game
swFeedbackGame = File.CreateText (UIManagerScript.SUBJECTID+"FeedbackGameData444.csv");
//write headers to file
swFeedbackGame.Write ("PositionRingFeeback" + "," + "PositionSphereMiddle" + "," + "distanceRingFeedbackTOSphere" + "," + "Collisions" + "," + "Timer"+System.Environment.NewLine);
}
public void SaveDataFeedback()
{
//start writing in file only when feedback game is starting
//if (StartButtonManager.startingGame) {
if (StartButtonManager.startingGame)
{
//get position of center of the ring
PositionRingFeedback = GameObject.Find ("Ring").transform.position;
//position of the center of the ring (y axis)
PositionRINGFeedback = PositionRingFeedback.y;
//error, meaning difference between position of the spheremiddle and center of the ring
distanceRingFeedbackTOSphere = PositionRINGFeedback - Sinewave.posSpheremiddle;
//write data to file _ columns are separated by a ,
swFeedbackGame.Write (PositionRINGFeedback + "," + Sinewave.posSpheremiddle + "," + distanceRingFeedbackTOSphere + "," + CounterManager.counterHitSinewave + "," + UIManagerScript.myTimer + System.Environment.NewLine);
swFeedbackGame.Flush();
}
else
{
swFeedbackGame.Close();
}
}
// Update is called once per frame
public void FixedUpdate()
{
//saves the data from the FeedbackGame every Frame
SaveDataFeedback();
}
你可以請妥善縮進代碼 –
似乎每次你重裝csv文件是重新創建,如果存在,那麼文本將appeand寫入前檢查,如果不存在則創建新文件 – Mostafiz
怎麼樣'使用內部初始化() {}塊,然後將流寫入器注入到'SaveDataFeedback()'而不是依賴全局實例? –