Save and Load using JSON file in Unity - c#
Save and Load using JSON file in Unity - c#
To save and load data using JSON files in Unity, you can use the JsonUtility
class, which is part of the UnityEngine namespace. This class provides methods for serializing objects to and from JSON format.
Example 1:
Here is an example of how you can use JsonUtility
to save and load data in Unity:
In this example, we have a SaveData
class that contains the data we want to save (the player's score and name). When the player presses the "S" key, we create an instance of SaveData
and populate it with the current values of score
and playerName
. We then use the JsonUtility.ToJson
method to convert the SaveData
object to a JSON string, which we write to a file called "save.json" using the File.WriteAllText
method.
When the game starts, we use the File.ReadAllText
method to read the contents of the "save.json" file into a string, and then use the JsonUtility.FromJson
method to convert the JSON string back into a SaveData
object. We can then assign the values from the SaveData
object to the score
and playerName
variables.
Note that the SaveData
class must have the System.Serializable
attribute in order for it to be serialized by JsonUtility
.
Example 2:
In Unity, you can use the JsonUtility
class to serialize and deserialize objects to and from JSON strings. Here's an example of how you can use it to save and load a simple object to and from a JSON file:
This example demonstrates how to save and load a Data
object, which has two fields: score
and name
. The JsonUtility.ToJson
method is used to convert the object to a JSON string, which is then saved to a file using the System.IO.File.WriteAllText
method. To load the object from the JSON file, the System.IO.File.ReadAllText
method is used to read the contents of the file into a string, and then the JsonUtility.FromJson
method is used to deserialize the string into a Data
object.
Keep in mind that this is just a simple example, and you may need to handle more complex cases (such as handling errors or missing fields) in your actual implementation.
Example 3:
To save data to a JSON file in Unity, you can use the JsonUtility
class which is part of Unity's UnityEngine.JsonUtility
namespace. Here's an example of how you can use JsonUtility
to save a simple data object to a JSON file:
To load data from a JSON file in Unity, you can use the JsonUtility.FromJson
method which deserializes a JSON string and returns an object of the specified type. Here's an example of how you can use JsonUtility.FromJson
to load a PlayerData
object from a JSON file:
Keep in mind that the data object you want to save or load with JsonUtility
must have the [System.Serializable]
attribute in order for it to be serialized or deserialized.
I hope this helps! Let me know if you have any questions.
Post a Comment
image video quote pre code