Search Unity

Saving ghost to disc during gameplay [Racing game]

Discussion in 'Scripting' started by kai_226, Feb 22, 2018.

  1. kai_226

    kai_226

    Joined:
    Jul 6, 2017
    Posts:
    53
    I am creating a racing game where the player can set a lap record and if he does, a ghost of that lap will be displayed.
    When the player achieves a lap record, I also want to store this ghost to disc. The data is basically a list containing the player's ID, the car he used [int] and a list of transforms that reflect position and rotation of a point in time.

    Currently I am simply calling the function from Update() [now bring the bats and punch me]! It works nice on my SSD but on my friends PC with a slower HDD, the game stutters when the saving occurs. I did read about either using a Coroutine or a Thread, I found this example which looks good but I don't know how/when to set workDone to true in that example.

    So, any suggestions what is the best way to save the ghost while the game is not paused?

    Here's the current saving code:
    Code (CSharp):
    1. public void SaveGhost(List<PointInTime> pointsInTime, float lapTime)
    2. {
    3.     string fileName = folderGhosts + @"/" + playerStats.playerID + "_" + trackNames[trackSelector] + ".gh";
    4.  
    5.     BinaryFormatter bf = new BinaryFormatter();
    6.     FileStream fs = File.Create(fileName);
    7.  
    8.     GhostContent gc = new GhostContent();
    9.     gc.playerID = playerStats.playerID;
    10.     gc.lapTime = lapTime;
    11.  
    12.     gc.pointsInTime = pointsInTime;
    13.  
    14.     bf.Serialize(fs, gc);
    15.     fs.Close();
    16.     gc = null;
    17. }
     
  2. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,196
    Well, what's the reason for saving this to disk while the game is busy running? Why can't you just hang on to that GhostContent object, and not write it to disk until later?
     
  3. If it's a PC game, I would write it on a separate thread. This task is fully describable, no need to attach back to the main thread or anything.

    Here you can find an example https://answers.unity.com/questions/936160/how-to-write-a-file-to-local-using-ienumerator.html (the reply, not the original).

    BUT!

    It does not help if the user has a HDD and you (or Unity) is streaming assets from the disk (textures, sound, etc).
    If the HDD is busy with your write, the game can't read those things.

    So ultimately I would postpone the write when the game isn't that busy.
     
  4. kai_226

    kai_226

    Joined:
    Jul 6, 2017
    Posts:
    53
    Thanks for your replies.
    Well, actually @dgoyette is right. At first I thought I should save it right away since the player could beat the record again in another lap during the same run, but actually I can just keep the new data and save it after the session!