在Unity中,序列化和反序列化是通過Unity自帶的JsonUtility類來實現的。JsonUtility類提供了靜態方法ToJson和FromJson,分別用于將對象序列化為JSON字符串和將JSON字符串反序列化為對象。
序列化示例代碼:
using UnityEngine;
[System.Serializable]
public class PlayerData
{
public string playerName;
public int playerLevel;
public float playerHealth;
}
public class SerializationExample : MonoBehaviour
{
void Start()
{
PlayerData player = new PlayerData();
player.playerName = "Player1";
player.playerLevel = 1;
player.playerHealth = 100f;
string json = JsonUtility.ToJson(player);
Debug.Log(json);
}
}
反序列化示例代碼:
using UnityEngine;
[System.Serializable]
public class PlayerData
{
public string playerName;
public int playerLevel;
public float playerHealth;
}
public class DeserializationExample : MonoBehaviour
{
void Start()
{
string json = "{\"playerName\":\"Player1\",\"playerLevel\":1,\"playerHealth\":100}";
PlayerData player = JsonUtility.FromJson<PlayerData>(json);
Debug.Log("Player Name: " + player.playerName);
Debug.Log("Player Level: " + player.playerLevel);
Debug.Log("Player Health: " + player.playerHealth);
}
}
在上面的示例中,我們定義了一個PlayerData類來存儲玩家的數據,然后通過JsonUtility.ToJson方法將PlayerData對象序列化為JSON字符串,再通過JsonUtility.FromJson方法將JSON字符串反序列化為PlayerData對象。最后我們可以通過訪問PlayerData對象的屬性來獲取反序列化后的數據。