Unity UI Toolkit을 이용한 캐릭터 선택 화면 생성하기

이 문서는 Unity를 사용하여 캐릭터 선택 화면을 만드는 방법에 대해 설명하며, UI 툴킷을 활용한 예제를 제공합니다. 이 예제에서는 리스트 뷰를 사용하여 캐릭터 목록을 표시하고, 선택된 캐릭터의 세부 정보를 보여줍니다.

개요

캐릭터 선택 화면은 왼쪽에 캐릭터 리스트가 있고, 오른쪽에 선택된 캐릭터의 세부 정보를 표시하는 구조로 구성됩니다. 아래의 단계별 가이드를 통해 이 UI를 구성할 수 있습니다.

선행 조건

  • Unity 에디터
  • UI 툴킷
  • 기본적인 C# 스크립팅

메인 UI 문서 생성

  1. UI 폴더 생성: 프로젝트의 Project 창에서 UI라는 이름의 폴더를 생성합니다.
  2. MainView.uxml 파일 생성:
  3. UI 폴더에 MainView.uxml 파일을 생성하고 다음 내용을 추가합니다.
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False">
    <Style src="MainView.uss" />
    <ui:VisualElement name="background">
        <ui:VisualElement name="main-container">
            <ui:ListView focusable="true" name="character-list" />
            <ui:VisualElement name="right-container">
                <ui:VisualElement name="details-container">
                    <ui:VisualElement name="details">
                        <ui:VisualElement name="character-portrait" />
                    </ui:VisualElement>
                    <ui:Label text="Label" name="character-name" />
                    <ui:Label text="Label" display-tooltip-when-elided="true" name="character-class" />
                </ui:VisualElement>
            </ui:VisualElement>
        </ui:VisualElement>
    </ui:VisualElement>
</ui:UXML>
  1. MainView.uss 파일 생성:
  2. UI 폴더에 MainView.uss라는 이름의 스타일시트를 생성하고 스타일링 코드를 추가합니다.
#background {
    flex-grow:1;
    align-items: center;
    justify-content: center;
    background-color: rgb(115, 37, 38);
}

#main-container {
    flex-direction: row;
    height:350px;
}

#character-list {
    width:230px;
    border-color: rgb(49, 26, 17);
    border-width:4px;
    background-color: rgb(110, 57, 37);
    border-radius:15px;
    margin-right:6px;
}

#character-name {
    -unity-font-style: bold;
    font-size:18px;
}

#character-class {
    margin-top:2px;
    margin-bottom:8px;
    padding-top:0;
    padding-bottom:0;
}

#right-container {
    justify-content: space-between; 
    align-items: flex-end;
}

#details-container {
    align-items: center; 
    background-color: rgb(170, 89, 57); 
    border-width:4px; 
    border-color: rgb(49, 26, 17);
    border-radius:15px;
    width:252px; 
    justify-content: center; 
    padding:8px;
    height:163px;
}

#details {
    border-color: rgb(49, 26, 17); 
    border-width:2px; 
    height:120px; 
    width:120px; 
    border-radius:13px; 
    padding:4px;
    background-color: rgb(255, 133, 84);
}

#character-portrait {
    flex-grow:1; 
    -unity-background-scale-mode: scale-to-fit;
}

리스트 엔트리 UI 문서 및 스타일 생성

  1. ListEntry.uxml 파일 생성:
  2. UI 폴더에 ListEntry.uxml 파일을 생성하고 아래의 내용을 추가합니다.
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False">
    <Style src="ListEntry.uss" />
    <ui:VisualElement name="list-entry">
        <ui:Label text="Label" display-tooltip-when-elided="true" name="character-name" />
    </ui:VisualElement>
</ui:UXML>
  1. ListEntry.uss 파일 생성:
  2. UI 폴더에 ListEntry.uss라는 이름의 스타일시트를 생성하고 다음 스타일을 추가합니다.
#list-entry {
    height:41px;
    align-items: flex-start;
    justify-content: center;
    padding-left:10px;
    background-color: rgb(170, 89, 57);
    border-color: rgb(49, 26, 17);
    border-width:2px;
    border-radius:15px;
}

#character-name {
    -unity-font-style: bold;
    font-size:18px;
    color: rgb(49, 26, 17);
}

샘플 데이터 생성

  1. Scripts 폴더 생성: Assets 폴더에 Scripts라는 폴더를 만들어 이곳에 스크립트를 저장합니다.
  2. CharacterData.cs 파일 생성:
  3. Scripts 폴더에 CharacterData.cs라는 파일을 생성하고 아래의 내용을 추가합니다.
using UnityEngine;

public enum ECharacterClass
{
    Knight, Ranger, Wizard
}

[CreateAssetMenu] 
public class CharacterData : ScriptableObject
{
    public string CharacterName;
    public ECharacterClass Class;
    public Sprite PortraitImage;
}

씬 설정

  1. SampleScene 생성: SampleScene에서 UIDocument 게임 오브젝트를 생성하고 UI 문서를 소스 에셋으로 추가합니다.
  2. 리스트 엔트리 및 메인 뷰의 컨트롤러 생성:
  3. 다음 두 개의 C# 스크립트를 생성합니다.
    • CharacterListEntryController.cs
    • CharacterListController.cs

CharacterListEntryController.cs:

using UnityEngine.UIElements;

public class CharacterListEntryController
{
    Label NameLabel;

    public void SetVisualElement(VisualElement visualElement)
    {
        NameLabel = visualElement.Q<Label>("character-name");
    }

    public void SetCharacterData(CharacterData characterData)
    {
        NameLabel.text = characterData.CharacterName;
    }
}

CharacterListController.cs:

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

public class CharacterListController
{
    VisualTreeAsset ListEntryTemplate;
    ListView CharacterList;
    Label CharClassLabel;
    Label CharNameLabel;
    VisualElement CharPortrait;

    public void InitializeCharacterList(VisualElement root, VisualTreeAsset listElementTemplate)
    {
        EnumerateAllCharacters();
        ListEntryTemplate = listElementTemplate;
        CharacterList = root.Q<ListView>("character-list");
        CharClassLabel = root.Q<Label>("character-class");
        CharNameLabel = root.Q<Label>("character-name");
        CharPortrait = root.Q<VisualElement>("character-portrait");

        FillCharacterList();
        CharacterList.onSelectionChange += OnCharacterSelected;
    }

    List<CharacterData> AllCharacters;

    void EnumerateAllCharacters()
    {
        AllCharacters = new List<CharacterData>();
        AllCharacters.AddRange(Resources.LoadAll<CharacterData>("Characters"));
    }

    void FillCharacterList()
    {
        CharacterList.makeItem = () =>
        {
            var newListEntry = ListEntryTemplate.Instantiate();
            var newListEntryLogic = new CharacterListEntryController();
            newListEntry.userData = newListEntryLogic;
            newListEntryLogic.SetVisualElement(newListEntry);
            return newListEntry;
        };

        CharacterList.bindItem = (item, index) =>
        {
            (item.userData as CharacterListEntryController).SetCharacterData(AllCharacters[index]);
        };

        CharacterList.fixedItemHeight = 45;
        CharacterList.itemsSource = AllCharacters;
    }

    void OnCharacterSelected(IEnumerable<object> selectedItems)
    {
        var selectedCharacter = CharacterList.selectedItem as CharacterData;

        if (selectedCharacter == null)
        {
            CharClassLabel.text = "";
            CharNameLabel.text = "";
            CharPortrait.style.backgroundImage = null;
            return;
        }

        CharClassLabel.text = selectedCharacter.Class.ToString();
        CharNameLabel.text = selectedCharacter.CharacterName;
        CharPortrait.style.backgroundImage = new StyleBackground(selectedCharacter.PortraitImage);
    }
}

메인 뷰에 컨트롤러 스크립트 연결

  1. MainView.cs 파일 생성:
  2. Scripts 폴더에 MainView.cs를 생성하고 아래의 코드를 추가합니다.
using UnityEngine;
using UnityEngine.UIElements;

public class MainView : MonoBehaviour
{
    [SerializeField]
    VisualTreeAsset ListEntryTemplate;

    void OnEnable()
    {
        var uiDocument = GetComponent<UIDocument>();
        var characterListController = new CharacterListController();
        characterListController.InitializeCharacterList(uiDocument.rootVisualElement, ListEntryTemplate);
    }
}
  1. UIDocument 선택 후 MainView.cs 추가:
  2. SampleScene에서 UIDocument를 선택하고 MainView.cs를 인스펙터 창의 Add Component로 드래그합니다.
  3. ListEntry Template 연결:
  4. ListEntry.uxmlListEntry Template 필드에 드래그하여 연결합니다.

마무리

위의 단계를 모두 완료하면 게임 모드에 전환했을 때, 게임 뷰에 캐릭터 선택 UI가 표시됩니다.

이를 통해 Unity의 UI 툴킷을 이용한 기본적인 UI 구조를 배우고, 발전시켜 나갈 수 있습니다. 추가적인 기능이나 디자인을 적용하여 자신의 캐릭터 선택 인터페이스를 더욱 풍부하게 만들 수 있습니다.

Read more

Unity 매뉴얼 스크립팅 API 해설

이 문서는 Unity의 매뉴얼 스크립팅 API에 대한 간단한 해설과 활용 예제들을 포함하고 있습니다. Unity는 게임 개발 플랫폼으로, 스크립팅 API를 통해 게임의 다양한 기능을 제어하고 수정할 수 있습니다. 버전 Unity 스크립팅 API는 여러 버전으로 제공됩니다. 주의 깊게 선택하여 사용하는 것이 중요합니다. 버전 설명 2023.2 최신 기능 및 버그 수정이 추가됨

By 이재협/실장/시스템개발실/PHYSIA

Unity 매뉴얼 스크립팅 API 설명서 해설

이 문서는 Unity의 매뉴얼 스크립팅 API에 대한 정보를 제공하며, 버전에 따라 다르게 적용되는 내용들을 설명합니다. 본 문서에서는 주요 내용을 간단히 정리하고 활용 가능 예제를 통해 이해를 돕겠습니다. 기본 개념 Unity에서 스크립팅 API는 게임 오브젝트와 그들의 동작을 제어하기 위한 강력한 도구입니다. 이를 통해 게임의 로직, 물리 엔진, 애니메이션 및 사용자 인터페이스를

By 이재협/실장/시스템개발실/PHYSIA

Unity 스크립팅 API 가이드

이 문서는 Unity의 스크립팅 API에 대해 설명합니다. Unity는 게임 개발을 위한 인기 있는 엔진으로, 강력한 스크립팅 기능을 제공합니다. 이 가이드는 Unity에서 스크립트를 작성하고 사용하는 방법을 이해하는 데 도움을 드립니다. 목차 * Unity 스크립팅 소개 * 기본 스크립트 생성 * 스크립트 사용 예제 * 응용 프로그램 * 참고 자료 Unity 스크립팅 소개 Unity는 C# 프로그래밍 언어를

By 이재협/실장/시스템개발실/PHYSIA