Unity Serialization 가이드
개요
Unity의 Serialization 시스템은 데이터 저장과 불러오기를 위한 편리한 방법을 제공합니다. JSON 및 Binary 형식으로 데이터를 직렬화하고 역직렬화할 수 있는 능력을 통해 개발자는 데이터를 효율적으로 관리할 수 있습니다.
버전 정보
- 최신 패키지 버전: 3.1.1 (Unity 에디터 2022.3용)
- 지원되는 Unity 버전:
- 2022.3 버전에서 사용 가능
- 하위 호환성: 3.0.0-pre.x, 2.1.x, 2.0.x 등
Serialization 설명
Serialization은 객체를 저장 가능한 형태로 변환하고, 이를 다시 객체로 복원하는 과정을 의미합니다. Unity에서는 이 과정을 통해 다양한 데이터 구조를 효율적으로 저장 및 불러올 수 있습니다.
주요 키워드
- 직렬화 (Serialization)
- JSON
- Binary
- Unity
활용 예제
1. JSON 직렬화 예제
아래는 C#을 사용하여 Unity에서 데이터를 JSON 형식으로 직렬화하는 간단한 예제입니다.
using UnityEngine;
using System.Collections.Generic;
using Newtonsoft.Json;
[System.Serializable]
public class PlayerData
{
public string playerName;
public int playerScore;
}
public class Example : MonoBehaviour
{
void Start()
{
PlayerData player = new PlayerData();
player.playerName = "Alice";
player.playerScore = 100;
// 객체를 JSON으로 변환
string json = JsonConvert.SerializeObject(player);
Debug.Log(json);
// JSON을 객체로 변환
PlayerData loadedPlayer = JsonConvert.DeserializeObject<PlayerData>(json);
Debug.Log(loadedPlayer.playerName);
}
}
2. Binary 직렬화 예제
Binary 형식을 사용하는 직렬화는 데이터 용량을 줄일 수 있어서 유용합니다.
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[System.Serializable]
public class PlayerData
{
public string playerName;
public int playerScore;
}
public class Example : MonoBehaviour
{
void Start()
{
PlayerData player = new PlayerData();
player.playerName = "Bob";
player.playerScore = 200;
// 객체를 Binary로 직렬화
BinaryFormatter formatter = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/playerData.dat");
formatter.Serialize(file, player);
file.Close();
// Binary 파일을 객체로 역직렬화
file = File.Open(Application.persistentDataPath + "/playerData.dat", FileMode.Open);
PlayerData loadedPlayer = (PlayerData)formatter.Deserialize(file);
file.Close();
Debug.Log(loadedPlayer.playerName);
}
}
추가 정보
다양한 Serialization 기능을 활용하면 Unity에서의 데이터 관리를 더욱 용이하게 할 수 있습니다. 필요한 경우, Unity의 공식 문서를 참조하여 더 많은 정보를 얻어보세요.
참고 문헌
- Unity 공식 매뉴얼
- Unity API 문서
- JSON.NET 라이브러리 (C#에서 JSON 직렬화에 유용)
이와 같은 방식으로 Serialization을 이해하고 활용하면 Unity에서의 데이터 관리를 더욱 효율적으로 할 수 있습니다.