직렬화(Serialization)

Stupidiot·2024년 9월 5일

Unity & C#

목록 보기
1/4

Serialization is the automatic process of transforming data structures or GameObject states into a format that Unity can store and reconstruct later.

즉, 게임 오브젝트 상태 및 데이터 구조를 다시 복구할 수 있는 포맷으로 변환하는 자동 프로세스

💡[SerializeField]를 인스펙터에 띄우는 용도로만 사용함 하지만 주된 목표는 저장-로드에 쓰임

직렬화 규칙(Serialization rules)

Serializer는 런타임에서 효율적으로 작동하도록 고안.

Serializers in Unity work directly on the fields of your C# classes rather than their properties

즉, Serializer는 클래스의 필드에서 직접 작동하기에 직렬화를 위한 규칙이 존재한다.

  • Is public, or has a SerializeField attribute
  • isn’t static
  • isn’t const
  • isn’t readonly
  • Has a field type that can be serialized:
    • Primitive data types (int, float, double, bool, string, etc.)
    • Enum types (32 bits or smaller)
    • Fixed-size buffers → unsafe
    • Unity built-in types, for example, Vector2, Vector3, Rect, Matrix4x4, Color, AnimationCurve
    • Serializable 속성이 있는 커스텀 구조체
    • UnityEngine.Object에서 파생된 오브젝트에 대한 레퍼런스
    • Serializable 속성이 있는 커스텀 클래스 - static X
    • 위에서 언급한 필드 타입의 배열
    • 위에서 언급한 필드 타입의 List<T>

💡Unity는 다차원 배열, 가변 배열, 딕셔너리, 중첩된 컨테이너 타입을 지원함
1. 클래스 또는 구조체에서 중첩된 타입 래핑
2. 직렬화 콜백 사용 →  ISerializationCallbackReceiver

SerializeReference

커스텀 클래스를 직렬화 할 때 사용할 방법중 하나

[SerializeReference] serialization: If you do specify [SerializeReference], Unity establishes the object as a managed reference. The host object still stores the objects directly in its serialized data, but in a dedicated registry section.

인라인 직렬화 : 효과적

[System.Serializable]
public class MyClass
{
    public int value;
}

public class Example : MonoBehaviour
{
    public MyClass field1;
    public MyClass field2;
}

SerializeReference 직렬화

public class Example : MonoBehaviour
{
    [SerializeReference] public MyClass field1;
    [SerializeReference] public MyClass field2;
}

프로퍼티 직렬화

일반적으로 직렬화 X

but, If a property has an explicit backing field, Unity serializes it

public int MyInt
{
    get => m_backing;
    private set => m_backing = value;
}

[SerializeField] private int m_backing;

💡인스펙터에서 프로퍼티 변수를 변경하면 set이 호출되나? → X 직접적으로 변경됩니다~

프리팹

프리팹도 하나 이상의 게임 오브젝트 및 컴포넌트가 직렬화된 데이터이다.

프리팹을 Instantiate하는 과정이 역직렬화

(프리팹 에디터를 실행하면 프리팹 인스턴스가 생성됩니다)

Best Serialization

  • 작은 data set Serialization - 이전 프로젝트 버전과 역호환성
  • 중복 data, cashed data 직렬화 X - 동기화되지 않을 가능성이 크다
profile
행복하세요

0개의 댓글