在Unity中,序列化和反序列化可以通過對對象進行標記和使用JsonUtility類來實現。
[System.Serializable]
public class PlayerData
{
public string playerName;
public int playerLevel;
}
然后,可以使用JsonUtility.ToJson方法將對象序列化為JSON格式的字符串:
PlayerData player = new PlayerData();
player.playerName = "Alice";
player.playerLevel = 10;
string jsonData = JsonUtility.ToJson(player);
string jsonData = "{\"playerName\":\"Bob\",\"playerLevel\":15}";
PlayerData player = JsonUtility.FromJson<PlayerData>(jsonData);
Debug.Log("Player Name: " + player.playerName);
Debug.Log("Player Level: " + player.playerLevel);
這樣就可以實現對象的序列化和反序列化操作。需要注意的是,JsonUtility類只支持Unity內置類型的序列化,對于自定義類型,需要手動實現序列化和反序列化方法。