Unity 커스텀 UI 컴포넌트 생성 가이드
개요
Unity의 UI 툴킷을 사용하여 커스텀 UI 요소를 생성하고 사용하는 방법을 설명합니다. 이 가이드는 프리팹 대신 UXML과 C#을 활용하여 재사용 가능한 UI 구성 요소를 만드는 방법에 중점을 둡니다.
주요 개념
프리팹과 UI 툴킷
- 프리팹: 씬에서 여러 번 사용될 수 있는 미리 만들어진 게임 오브젝트.
- UI 툴킷: UI 요소가 게임 오브젝트가 아니므로 프리팹 개념을 사용할 수 없음. 대신 UXML을 사용해 UI 구조를 정의하고, USS로 스타일을 설정하며, C#으로 로직을 구현합니다.
재사용 가능한 UI 컴포넌트 생성
예를 들어, 캐릭터의 이미지, 생명력, 공격 통계를 표시하는 카드(CardElement
)를 생성하는 방법에 대해 설명합니다.
단계
- C#에서
CardElement
커스텀 요소 선언 - UXML에서 커스텀 컨트롤의 계층 구조 정의
- 두 가지 방식: UXML 우선 방식 및 요소 우선 방식
- 커스텀 컨트롤의 자식 요소에 대한 레퍼런스 찾기
- C# 클래스에서 로직 캡슐화
- 게임 코드와 연결하기
UXML 우선 방식
- 우선 설정: UXML 문서에
CardElement
를 추가하고, 자식 요소를 해당 아래에 선언. - 이는 고정된 UI 구조를 포함하는 간편한 솔루션입니다.
예시 C# 및 UXML 코드:
// CardElement 정의
using UnityEngine;
using UnityEngine.UIElements;
// Define the custom control type.
public class CardElement : VisualElement
{
public new class UxmlFactory : UxmlFactory<CardElement> {}
private VisualElement portraitImage => this.Q("image");
private Label attackBadge => this.Q<Label>("attack-badge");
private Label healthBadge => this.Q<Label>("health-badge");
public void Init(Texture2D image, int health, int attack)
{
portraitImage.style.backgroundImage = image;
attackBadge.text = health.ToString();
healthBadge.text = attack.ToString();
}
}
<ui:UXML xmlns:ui="UnityEngine.UIElements" editor-extension-mode="False">
<Style src="CardElementUI.uss" />
<CardElement>
<ui:VisualElement name="image" />
<ui:VisualElement name="stats">
<ui:Label name="attack-badge" />
<ui:Label name="health-badge" />
</ui:VisualElement>
</CardElement>
</ui:UXML>
요소 우선 방식
- 우선 설정: UXML 문서에 자식 요소만 포함하고 C#에서 로드.
- 이는 더 유연한 UI 구조를 제공합니다.
예시 C# 및 UXML 코드:
// CardElement 정의
using UnityEngine;
using UnityEngine.UIElements;
// Define the custom control type.
public class CardElement : VisualElement
{
public new class UxmlFactory : UxmlFactory<CardElement> {}
private VisualElement portraitImage => this.Q("image");
private Label attackBadge => this.Q<Label>("attack-badge");
private Label healthBadge => this.Q<Label>("health-badge");
public CardElement()
{
var asset = Resources.Load<VisualTreeAsset>("CardElement");
asset.CloneTree(this);
}
}
<ui:UXML xmlns:ui="UnityEngine.UIElements" editor-extension-mode="False">
<CardElement />
</ui:UXML>
C#에서의 인스턴스화
게임 내에서 CardElement
를 인스턴스화하는 방법:
using UnityEngine;
using UnityEngine.UIElements;
public class UIManager : MonoBehaviour
{
public void Start()
{
UIDocument document = GetComponent<UIDocument>();
foreach (Card card in GetCards())
{
var cardElement = new CardElement(card.image, card.health, card.attack);
document.rootVisualElement.Add(cardElement);
}
}
}
권장 사항
- 프로젝트 UI가 복잡해질수록 로직을 더 높은 레벨의 컴포넌트로 분리할 것을 권장합니다.
- 이 원칙을 적용하면 UI를 더 쉽게 관리할 수 있으며, 사용자의 요구에 따라 다양한 UI 구조를 구현할 수 있습니다.
추가 리소스
- UQuery로 시각적 요소 찾기
- UXML 인스턴스를 템플릿으로 사용
- UXML 파일 재사용
- 런타임 UI 지원
이 가이드는 Unity의 UI 툴킷을 활용하여 강력하고 유연한 UI 시스템을 구축하는 데 필요한 기본 지식을 제공합니다.