unity

[Unity] - JSON 파일 저장하고 불러오기

chyam_eun 2025. 6. 4. 20:12

save.json 파일에 저장하고, 저장된 여러 명의 플레이어 데이터를 불러와서 콘솔에 출력하기

{
  "players": [
    { "nickname": "배달원", "level": 0, "coin": 0 },
    { "nickname": "배달원22", "level": 0, "coin": 0 }
  ]
}

save.json 파일은 위와같음. "players"라는 이름으로 이 리스트를 감싸줘야함.

 

[System.Serializable]
public class PlayerData
{
    public string nickname;
    public int level;
    public int coin;
}

[System.Serializable]
public class PlayerDataList
{
    public List<PlayerData> players;
}

JSON에서 읽을 수 있게 해주기 위해서 [System.Serializable]을 꼭 해줘야함. 

 

PlayerDataList 클래스는 PlayerData들을 여러명 모아놓은 리스트를 담은 것.(=>래퍼 클래스)

  • JsonUtility는 단순한 JSON만 다룰 수 있어서 [{...},{...}] 와 같은 배열만 있는 구조는 못 읽음.
  • { "players" : [{...},{...}] }와 같이 키로 감싸진 구조만 읽을 수 있어서 꼭 필요함.

 

public static DataManager instance;

private void Awake()
{
    if (instance == null)
    {
        instance = this;
    }
    else if (instance == this)
    {
        Destroy(instance.gameObject);
    }
    DontDestroyOnLoad(this.gameObject);
}

싱글톤 패턴.

DataManager 인스턴스가 하나만 존재하도록 함. 씬이 바껴도 파괴되지 않도록 유지.

 

path = Application.dataPath + "/";

경로를 설정해줌. Application.dataPath는 Unity 프로젝트의 Assets/ 폴더 경로임.

 

아래는 추가하는게 아니라 덮어쓰는 방식임.

public void SaveData()
{
    // 여러 명의 플레이어 데이터 생성
    PlayerData player1 = new PlayerData { nickname = "배달원1", level = 0, coin = 0 };
    PlayerData player2 = new PlayerData { nickname = "배달원222", level = 0, coin = 0 };

    List<PlayerData> playerList = new List<PlayerData> { player1, player2 };

    // 리스트를 래퍼 객체로 감쌈
    PlayerDataList wrapper = new PlayerDataList();
    wrapper.players = playerList;

    // JSON으로 직렬화
    string json = JsonUtility.ToJson(wrapper, true); // true는 보기 좋게 포맷팅

    // 저장
    File.WriteAllText(path + filename, json);
    Debug.Log("저장 완료: " + path + filename);
}

 

public void LoadData()
{
    string fullPath = path + filename; // ...Assets/save.json

    if (!File.Exists(fullPath)) // 파일이 존재하지 않으면 에러
    {
        Debug.LogError("Save file not found at: " + fullPath);
        return;
    }

    string data = File.ReadAllText(fullPath); // JSON 텍스트를 읽음
    PlayerDataList playerList = JsonUtility.FromJson<PlayerDataList>(data); //PlayerDataList객체로 역직렬화 함.

    if (playerList == null || playerList.players == null) // JSON을 잘못만들었거나 구조 안맞으면 에러
    {
        Debug.LogError("playerList or playerList.players is null. Check JSON format.");
        return;
    }

    foreach (PlayerData player in playerList.players) // 각 플레이어 정보 출력 
    {
        Debug.Log($"Nickname: {player.nickname}, Level: {player.level}, Coin: {player.coin}");
    }
}

역직렬화 : JSON -> 객체 (파일을 불러올 때)

직렬화 : 객체 -> JSON (파일을 저장할 때)

using System.Collections.Generic;
using UnityEngine;
using System.IO;

[System.Serializable]
public class PlayerData
{
    public string nickname;
    public int level;
    public int coin;
}

[System.Serializable]
public class PlayerDataList
{
    public List<PlayerData> players;
}

public class DataManager : MonoBehaviour
{
    public static DataManager instance;

    string path;
    string filename = "save.json";

    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else if (instance == this)
        {
            Destroy(instance.gameObject);
        }

        DontDestroyOnLoad(this.gameObject);

        path = Application.dataPath + "/";
        Debug.Log("Save Path: " + path);
    }

    void Start()
    {
        SaveData();
        LoadData();
    }
    public void SaveData()
    {
        PlayerData player1 = new PlayerData { nickname = "배달원1", level = 0, coin = 0 };
        PlayerData player2 = new PlayerData { nickname = "배달원222", level = 0, coin = 0 };

        List<PlayerData> playerList = new List<PlayerData> { player1, player2 };

        PlayerDataList wrapper = new PlayerDataList();
        wrapper.players = playerList;

        string json = JsonUtility.ToJson(wrapper, true);

        File.WriteAllText(path + filename, json);
        Debug.Log("저장 완료: " + path + filename);
    }

    public void LoadData()
    {
        string fullPath = path + filename;

        if (!File.Exists(fullPath))
        {
            Debug.LogError("Save file not found at: " + fullPath);
            return;
        }

        string data = File.ReadAllText(fullPath);
        PlayerDataList playerList = JsonUtility.FromJson<PlayerDataList>(data);

        if (playerList == null || playerList.players == null)
        {
            Debug.LogError("playerList or playerList.players is null. Check JSON format.");
            return;
        }

        foreach (PlayerData player in playerList.players)
        {
            Debug.Log($"Nickname: {player.nickname}, Level: {player.level}, Coin: {player.coin}");
        }
    }
}