본문 바로가기
개발/Unity

Unity) SerializeField / SerializeReference

by 테샤르 2022. 8. 30.

SerializeField / SerializeReference

 

Unity 의 Field 항목를 직렬화 할때는 SerializeField를 사용한다.

직렬화 가능한 항목은 다음과 같다.

< 직렬화 가능한 항목 >

UnityEngine.Object를 상속하는 클래스 ( GameObject, Compoent, MonoBehaviour, Texture 2D, AnimationClip 등등)
int, string, float, bool 같은 기본 원시 데이터 유형
Vector2, Vector3, Vector4, Quaternion,Matrix4x4, Color, Rect, LayerMask 등 기본 제공 유형
Enum, Struct
직렬화 가능한 배열, 목록, System.Serialize가 명시된 Class

 

Unity 2019.3 에서 추가된 직렬화 개선 사항으로 
C# 클래스 값 유형이 아닌 레퍼런스를 기반으로 직렬화를 지원해서 사용이 가능하다.

이것이 SerializeReference이다.

 

 

반응형

< SerializeReference >

SerializeReference 예시 코드는 다음과 같다.

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

public interface IShape {}
[Serializable]
public class Cube : IShape
{
    public Vector3 size;
}
[ExecuteInEditMode]
public class BuildingBlocks : MonoBehaviour
{
    [SerializeReference]
    public List<IShape> inventory;
   void OnEnable()
    {
        if (inventory == null)
        {
            inventory = new List<IShape>()
            {
                new Cube() {size = new Vector3(1.0f, 1.0f, 1.0f)}
            };
            Debug.Log("Created list");
        }
        else
            Debug.Log("Read list");
    }
}
using System;
using UnityEngine;

public class SerializeReferencePolymorphismExample : MonoBehaviour
{
    [Serializable]
    public class Base
    {
        public int m_Data = 1;
    }

    [Serializable]
    public class Apple : Base
    {
        public string m_Description = "Ripe";
    }

    [Serializable]
    public class Orange : Base
    {
        public bool m_IsRound = true;
    }

    // Use SerializeReference if this field needs to hold both
    // Apples and Oranges.  Otherwise only m_Data from Base object would be serialized
    [SerializeReference]
    public Base m_Item = new Apple();

    [SerializeReference]
    public Base m_Item2 = new Orange();

    // Use by-value instead of SerializeReference, because
    // no polymorphism and no other field needs to share this object
    public Apple m_MyApple = new Apple();
}

 

Unity SerializeReference : [링크]

 

Unity - Scripting API: SerializeReference

See the serialization manual page for information about serialization and the complete serialization rules. Without the use of the [SerializeReference] attribute, Unity serializes each of the fields of an object by value or by reference, depending on the f

docs.unity3d.com

Unity SerailizeField : [링크]

 

Unity - Scripting API: SerializeField

When Unity serializes your scripts, it only serializes public fields. If you also want Unity to serialize your private fields you can add the SerializeField attribute to those fields. Unity serializes all your script components, reloads the new assemblies,

docs.unity3d.com

 

★☆☆☆☆

 

반응형

댓글