Modelo

  • EN
    • English
    • Español
    • Français
    • Bahasa Indonesia
    • Italiano
    • 日本語
    • 한국어
    • Português
    • ภาษาไทย
    • Pусский
    • Tiếng Việt
    • 中文 (简体)
    • 中文 (繁體)

How to Save Objects in Unity

Oct 14, 2024

When developing games in Unity, it's important to know how to save and load game objects to maintain progress and state. One way to achieve this is through JSON serialization, which allows you to convert complex data types, such as objects, into a string format that can be easily stored and retrieved. Here's a step-by-step guide on how to save objects in Unity using JSON serialization.

Step 1: Prepare the Object

Before we can save an object, we need to define a class for the object that we want to save. This class should have the [Serializable] attribute, and its properties should also be serializable. For example, let's say we have a class called Player that we want to save:

[System.Serializable]

public class Player

{

public string playerName;

public int playerScore;

}

Step 2: Convert Object to JSON

Once we have the object class defined, we can convert an instance of the class to JSON using the JsonUtility class provided by Unity. Here's an example of how to convert an instance of the Player class to JSON:

Player player = new Player();

player.playerName = "John";

player.playerScore = 100;

string json = JsonUtility.ToJson(player);

Step 3: Save JSON to File

After converting the object to JSON, we can save the JSON string to a file using the File class provided by Unity. Here's an example of how to save the JSON string to a file:

string path = Application.persistentDataPath + "/playerData.json";

File.WriteAllText(path, json);

Step 4: Load JSON from File

To load the saved object, we can read the JSON string from the file and convert it back to an object using the JsonUtility class. Here's an example of how to load the saved object from the file:

string loadedJson = File.ReadAllText(path);

Player loadedPlayer = JsonUtility.FromJson(loadedJson);

Now that we've loaded the saved object from the file, we can use the loadedPlayer instance to resume the game from where it was previously saved.

By following these steps, you can effectively save and load game objects in Unity using JSON serialization. This allows you to maintain the state and progress of your game, providing a seamless and enjoyable experience for players.

Recommend