Writing data to a file
Just as we may wish to read data from a file, there are times when it is useful to save data to a file. For example, we may want to save data from our game into our local computer, whether for debugging, recording game testing experiments, and so on.
In this recipe, we’ll declare a data structure for player’s names and scores, and save the data for a player as a JSON text file.
Figure 10.13: Player name and score data saved as a JSON text file
How to do it...
To write data to a file, perform the following steps:
- Create a new Unity 2D project.
- Create a new, empty folder in the Project panel, named Data. We’ll write our JSON text file into this folder.
- Create a new C# script class,
PlayerScore
, with the following code:using UnityEngine; using System; [Serializable] public class PlayerScore { public string name; public int score; public string ToJson() { bool prettyPrintJson...