티스토리 뷰

728x90
반응형

 

타이틀 이미지

데이터 저장 방식 개요

게임 개발에서 데이터를 저장할 때 선택할 수 있는 방법은 여러 가지가 있습니다. 이번 글에서는 Unity에서 자주 사용하는 세 가지 방법인 PlayerPrefs, JSON, 그리고 Binary 저장 방식을 비교하고, 각각의 코드 예제를 소개합니다.

한 줄 요약: 사용할 데이터 크기와 보안 요구 사항에 따라 적합한 저장 방식을 선택하세요.

PlayerPrefs

간단한 키-값 (key-value) 형태의 데이터를 저장할 수 있으며, 주로 게임 설정과 같은 간단한 데이터에 적합합니다.

// PlayerPrefs 예제 코드
using UnityEngine;

public class PlayerPrefsExample : MonoBehaviour
{
    void SaveData()
    {
        PlayerPrefs.SetInt("PlayerScore", 100);
        PlayerPrefs.SetString("PlayerName", "Max");
        PlayerPrefs.Save(); // 명시적으로 저장
    }

    void LoadData()
    {
        int playerScore = PlayerPrefs.GetInt("PlayerScore", 0); // 기본값을 0으로 설정
        string playerName = PlayerPrefs.GetString("PlayerName", "Unknown");
        Debug.Log($"Loaded Data - Name: {playerName}, Score: {playerScore}");
    }
}
참고: PlayerPrefs는 값이 문자열로 변환되어 저장되므로 보안이 필요한 데이터에는 적합하지 않습니다.

JSON

Human-readable 형식으로 데이터를 저장할 수 있으며, 복잡한 데이터 구조에 유용합니다. JSON은 데이터를 직렬화하여 저장하고, 프로그램 시작 시 다시 파싱할 수 있습니다.

// JSON 직렬화 예제 코드
using UnityEngine;
using System.IO;

[System.Serializable]
public class PlayerData
{
    public string Name;
    public int Score;
}

public class JsonExample : MonoBehaviour
{
    private string filePath;

    void Awake()
    {
        filePath = Path.Combine(Application.persistentDataPath, "playerData.json");
    }

    public void SaveData()
    {
        PlayerData data = new PlayerData { Name = "Max", Score = 100 };
        string json = JsonUtility.ToJson(data);
        File.WriteAllText(filePath, json);
    }

    public void LoadData()
    {
        if (File.Exists(filePath))
        {
            string json = File.ReadAllText(filePath);
            PlayerData data = JsonUtility.FromJson(json);
            Debug.Log($"Loaded Data - Name: {data.Name}, Score: {data.Score}");
        }
    }
}
⚠️ 주의: JSON은 텍스트로 저장되므로 민감한 데이터를 보호하는 데는 취약합니다.

Binary

이진 파일 형식으로 직렬화 및 저장할 수 있어, 보안이 중요한 데이터에 적합합니다. 다만, 사람이 읽을 수 없기 때문에 디버깅이 어려울 수 있습니다.

// Binary 직렬화 예제 코드
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

[System.Serializable]
public class PlayerBinaryData
{
    public string Name;
    public int Score;
}

public class BinaryExample : MonoBehaviour
{
    private string filePath;

    void Awake()
    {
        filePath = Path.Combine(Application.persistentDataPath, "playerData.dat");
    }

    public void SaveData()
    {
        PlayerBinaryData data = new PlayerBinaryData { Name = "Max", Score = 100 };
        BinaryFormatter formatter = new BinaryFormatter();
        using (FileStream stream = new FileStream(filePath, FileMode.Create))
        {
            formatter.Serialize(stream, data);
        }
    }

    public void LoadData()
    {
        if (File.Exists(filePath))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            using (FileStream stream = new FileStream(filePath, FileMode.Open))
            {
                PlayerBinaryData data = (PlayerBinaryData)formatter.Deserialize(stream);
                Debug.Log($"Loaded Data - Name: {data.Name}, Score: {data.Score}");
            }
        }
    }
}
Tip: Binary Format은 데이터 암호화에 유리하지만 Unity 웹 빌드에선 지원하지 않으므로 플랫폼에 맞게 사용해야 합니다.
728x90
반응형
LIST
글 보관함
최근에 올라온 글
160x600