Hello , this is Mahsa
Is there anyone to explain JsonUtility
very well ? help me out
Hello , this is Mahsa
Is there anyone to explain JsonUtility
very well ? help me out
JSON (JavaScript Object Notation): is a data interchange format, used to store and exchange data between a server and a client, or between different software components. JSON is easy for both humans to read and write, and for machines to parse.
Unity’s JsonUtility: is a built-in class that helps you work with JSON data in Unity. It allows you to convert between JSON and C#. You can serialize (convert) C# objects or structure into JSON and deserialize (convert) JSON into C#. This is useful for saving and loading game data, sending and receiving data over a network, or working with any kind of structured data.
// Only plain classes and structures are supported;
// classes derived from UnityEngine.Object (such as MonoBehaviour or ScriptableObject) are not.
public class PlayerData
{
public string playerName;
public int playerScore;
}
public void SavePlayer()
{
PlayerData playerData = new PlayerData();
playerData.playerName = "John";
playerData.playerScore = 100;
string json = JsonUtility.ToJson(playerData);
// Saves as a text file, this will be store in the computer even after closing the game
File.WriteAllText(Application.persistentDataPath + "/playerData.json", json);
}
private void LoadPlayer()
{
string path = Application.persistentDataPath + "/playerData.json";
if (File.Exists(path))
{
string json = File.ReadAllText(path);
PlayerData loadedData = JsonUtility.FromJson<PlayerData>(json);
// After caling SavePlayer() this will restore the saved "John" and "100"
Debug.Log("Player Name: " + loadedData.playerName);
Debug.Log("Player Score: " + loadedData.playerScore);
}
else
{
Debug.Log("No saved player data found.");
}
}