Serializable
Serializable 속성을 클래스나 구조체에 적용하면 Unity의 인스펙터 창에서 해당 클래스나 구조체의 필드를 편집할 수 있게 된다. 예를 들어, 게임의 캐릭터 정보나 아이템 데이터 등을 인스펙터 창에서 쉽게 설정할 수 있게 해준다.
Item이라는 클래스를 정의하고, 이 클래스를 인스펙터 창에서 편집할 수 있도록 했다.
Item 클래스 정의:
[System.Serializable]
public class Item
{
public string itemName;
public int itemID;
public float itemWeight;
}
Inventory 스크립트에서 사용:
using UnityEngine;
public class Inventory : MonoBehaviour
{
public Item[] items;
}
Unity 에디터에서 확인:
Inventory 스크립트를 붙인 게임 오브젝트를 선택했을 때 인스펙터 창에서 items 배열을 편집할 수 있게 된다.
Item 클래스가 직렬화 가능하기 때문에, 배열의 각 요소에 대해 itemName, itemID, itemWeight 필드를 인스펙터에서 설정할 수 있다.
Item 클래스:
System.Serializable 속성을 사용하여 클래스가 직렬화 가능하다는 것을 Unity에 알려준다.
이 클래스는 itemName, itemID, itemWeight라는 세 개의 공용 필드를 가지고 있다.
Inventory 클래스:
MonoBehaviour를 상속받아 Unity 컴포넌트로 사용될 수 있다.
Item 객체들의 배열인 items를 선언하여 여러 개의 Item 객체를 저장할 수 있다.
직렬화는 데이터를 구조화하고 인스펙터에서 쉽게 편집할 수 있도록 하는 데 매우 유용하다. 게임 캐릭터의 능력치를 설정하는 CharacterStats 클래스를 만들어 보자.
CharacterStats 클래스 정의:
[System.Serializable]
public class CharacterStats
{
public string characterName;
public int health;
public int mana;
public int strength;
public int agility;
}
Character 스크립트에서 사용:
using UnityEngine;
public class Character : MonoBehaviour
{
public CharacterStats stats;
}
Unity 에디터에서 확인:
위 스크립트를 저장하고 Unity 에디터로 돌아가면, Character 스크립트를 붙인 게임 오브젝트를 선택했을 때 인스펙터 창에서 stats 필드를 편집할 수 있게 된다.
CharacterStats 클래스가 직렬화 가능하기 때문에, 각 캐릭터의 characterName, health, mana, strength, agility 필드를 인스펙터에서 설정할 수 있다.
요약
Serializable을 사용하면 복잡한 데이터 구조를 쉽게 관리하고 인스펙터에서 편집할 수 있게 된다. 이는 게임 개발 시 데이터 관리와 디버깅을 더욱 편리하게 해준다.