Unity/게임 개발 스터디

게임 개발 스터디 6 : UI Toolkit - C# script를 사용하여 추가하는 방법

sorry0101 2022. 9. 13. 18:16

1. 다음과 같이 코드를 작성한다. (상세한 설명은 주석처리)

using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements; // UI Control을 사용하기 위한 선언
using UnityEditor.UIElements;

public class CharacterBuilder : EditorWindow
{
	// Menu Root를 지정할 수 있습니다
    [MenuItem("Character/CharacterBuilder")]
    // Window 생성 코드
    public static void ShowExample()
    {
        CharacterBuilder wnd = GetWindow<CharacterBuilder>();
        wnd.titleContent = new GUIContent("CharacterBuilder");
    }

	// Widow 에 보여질 GUI
    public void CreateGUI()
    {
        // Each editor window contains a root VisualElement object
        VisualElement root = rootVisualElement;

        // VisualElements objects can contain other VisualElement following a tree hierarchy.
        // Label(Text와 동일)
        VisualElement label = new Label("Character Tool C# Code!!");
        root.Add(label);

		// UI 컨트롤을 창에 추가하려면 요소 클래스를 인스턴스화한 다음 
        // rootVisualElement로 add 해주어야 한다.
        Button button = new Button();
        button.name = "Character Info";
        button.text = "Character Info";
        rootVisualElement.Add(button);

        Toggle toggle = new Toggle();
        toggle.name = "Dealer";
        toggle.label = "Dealer";
        rootVisualElement.Add(toggle);

        #region UXML
        // Import UXML
        var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Character/Editor/CharacterBuilder.uxml");
        VisualElement labelFromUXML = visualTree.Instantiate();
        root.Add(labelFromUXML);

        // A stylesheet can be added to a VisualElement.
        // The style will be applied to the VisualElement and all of its children.
        var styleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/Character/Editor/CharacterBuilder.uss");
        VisualElement labelWithStyle = new Label("Hello World! With Style");
        labelWithStyle.styleSheets.Add(styleSheet);
        root.Add(labelWithStyle);
        #endregion
    }
}

2. Window에서 변경된 것을 확인 할 수 있다.

- Dealer 토글까지의 영역이 C#으로 변경한 내용이다.