유니티 Attribute - 직렬화로 Inspector에 보여주기
private와 같은 비공개 변수를 인스펙터에서 보고 싶을 때, [SerializeField] 속성을 사용한다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SerializableTest : MonoBehaviour
{
[SerializeField]
private int a;
}
private으로 선언했는데도 변수 a가 보이는 것을 알 수 있다.

이제 Vector3 배열을 public으로 선언해보자.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SerializableTest : MonoBehaviour
{
public Vector3[] v3;
}
스크립트를 적당한 오브젝트에 추가하면 아래와 같이 스크립트가 추가된다.

V3 옆에 배열의 길이를 지정하면 Element가 생겨서 값을 정할 수 있다.

이제 임의로 만든 Struct를 배열로 선언해보자.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SerializableTest : MonoBehaviour
{
public struct MyStruct
{
public Vector2 v2;
public Vector3 v3;
public Material mat;
}
public MyStruct[] ms;
public Vector3[] v3;
}
스크립트에 변화가 없다.

using System; 을 선언한 후 해당 struct에 직렬화 [Serializable]를 추가한다.
using System; /* import for Serializable */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SerializableTest : MonoBehaviour
{
[Serializable] /* 직렬화 */
public struct MyStruct
{
public Vector2 v2;
public Vector3 v3;
public Material mat;
}
...
인스펙터에서 구조체의 필드 Ms가 추가된 것을 알 수 있다.

그리고 배열의 길이를 설정하면 struct의 멤버 변수를 설정할 수 있다.

직렬화는 메모리 내부의 오브젝트를 내보내기 위해서 변환하는 것이다.
유니티에서는 객체를 유니티 Editor가 저장하고 재구성할 수 있도록 변환하는 프로세스이다.
직렬화를 위해서는 아래의 규칙이 필요하다.
- public이거나 SerializeField 속성이 있어야 함.
- static, const, readonly가 아님.
- 직렬화할 수 있는 filedtype (단순 필드 타입)이 있어야 한다.
직렬화에 대한 Unity Documentation 링크 참고
Unity Plus:
Easy 2D, 3D, VR, & AR software for cross-platform development of games and mobile apps. - Unity Store
Have a 2D, 3D, VR, or AR project that needs cross-platform functionality? We can help. Take a look at the easy-to-use Unity Plus real-time dev platform!
store.unity.com
Unity Pro:
Unity Pro
The complete solutions for professionals to create and operate.
unity.com
Unity 프리미엄 학습:
Unity Learn
Advance your Unity skills with live sessions and over 750 hours of on-demand learning content designed for creators at every skill level.
unity.com