Day - 06. UI Toolkit 살펴 보기

Unity3D 2021. 11. 4. 23:23
반응형

어제 하던거 이어서 Templates 부터 보겠습니다 ~

 

이전 포스팅은 https://smilejsu.tistory.com/2324 를 참고해주세요 

 

시작합니다 

 

https://docs.unity3d.com/Manual/UIE-ElementRef.html

 

Unity - Manual: UXML elements reference

UXML elements reference The following tables outline the UXML elements available in the UnityEngine.UIElements and UnityEditor.UIElements namespaces. Base elements Element Function Namespace Permitted child elements Attributes VisualElement The base class

docs.unity3d.com

 

 

Templates

https://docs.unity3d.com/ScriptReference/UIElements.TemplateContainer.html

Element Function Namespace Permitted child elements (허용되는 자식 요소) Attributes
Template Instance 요소를 사용하여 인스턴스화할 수 있는 다른 UXML 템플릿에 대한 참조입니다. UnityEngine.UIElements None name, path

name: 이 요소에 대한 고유한 문자열 식별자

path: 로드할 UXML 파일의 경로

 

src속성을 path대신 사용

https://forum.unity.com/threads/questions-about-template-path-and-schemelocation-in-uxml.677806/

 

템플릿은 Day3 https://smilejsu.tistory.com/2322 때 했었던거 같네요  

 

실습해보기

 

템플릿을 만들고 (Template.uxml)

간단하게 label만 넣어줬습니다 

<?xml version="1.0" encoding="utf-8"?>
<engine:UXML
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:engine="UnityEngine.UIElements"
    xmlns:editor="UnityEditor.UIElements"
    xsi:noNamespaceSchemaLocation="../../UIElementsSchema/UIElements.xsd"
>
  <engine:Label name="player-name-label" text="default name" />

</engine:UXML>

 

Template.uxml 파일을 선택하면 인스펙터창에서 확인해볼수 있어요 

 

Editor Window를 만들어줍니다

자동으로 윈도우창이 열립니다 

 

MyWindow.uxml에서 템플릿을 사용해요 

<?xml version="1.0" encoding="utf-8"?>
<engine:UXML
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:engine="UnityEngine.UIElements"
    xmlns:editor="UnityEditor.UIElements"
    xsi:noNamespaceSchemaLocation="../../UIElementsSchema/UIElements.xsd"
>
  <engine:Template src="/Assets/Editor/Template.uxml" name="Template"/>
  <engine:Instance name="player1" template="Template"></engine:Instance>
  
</engine:UXML>

템플릿 속성을 재정의 해봅니다 

<?xml version="1.0" encoding="utf-8"?>
<engine:UXML
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:engine="UnityEngine.UIElements"
    xmlns:editor="UnityEditor.UIElements"
    xsi:noNamespaceSchemaLocation="../../UIElementsSchema/UIElements.xsd"
>
  
  <engine:Template src="/Assets/Editor/Template.uxml" name="Template"/>
  <engine:Instance name="player1" template="Template">
    <AttributeOverrides element-name="player-name-label" text="Alice" />
  </engine:Instance>
  
</engine:UXML>

 

 

경고가 있긴 한데 이게 먼지 아직은 잘 모르겠네요 

공백? 콘텐츠 모델이 비어있습니다..?

음; 일단 진행 합니다 


 

 

 

 

Templates

https://docs.unity3d.com/Manual/UIE-ElementRef.html

 

Element Function Namespace Permitted child elements (허용되는 자식 요소) Attributes
Instance 템플릿의 인스턴스 UnityEngine.UIElements None
template

 

template: 인스턴스화할 템플릿의 이름

 

인스턴스는 위 실습에서 MyWindow에서 Template을 로드 하고 나서 사용했었습니다 

 ...
 
 <engine:Instance name="player1" template="Template">
 
 ...

 

 

Templates

https://docs.unity3d.com/Manual/UIE-ElementRef.html

https://docs.unity3d.com/ScriptReference/UIElements.TemplateContainer.html

https://stephenhodgson.github.io/UnityCsReference/api/UnityEngine.Experimental.UIElements.TemplateContainer.html

https://docs.unity3d.com/Packages/com.unity.ui@1.0/api/UnityEngine.UIElements.TemplateContainer.html

 

TemplateContainer 인스턴스는 UXML 파일의 루트를 나타내기 위해 Unity에 의해 생성되며 파일의 모든 요소에 대한 부모 역할을 합니다. 

 

사용자는 일반적으로 TemplateContainer 개체를 직접 만들지 않습니다. 

 

Instantiate()를 사용하면 계층 구조의 루트를 나타내기 위해 TemplateContainer 인스턴스가 반환됩니다. 

 

UXML 템플릿을 사용할 때 템플릿 인스턴스에 대해 TemplateContainer가 생성되고 상위 UXML 파일의 계층 구조에 삽입됩니다.

 

Element Function Namespace Permitted child elements (허용되는 자식 요소) Attributes
TemplateContainer 템플릿 컨테이너입니다. UnityEngine.UIElements None BindableElement의 모든 속성 

template

template: 이 템플릿의 문자열 식별자

 

 

반응형

 

 


 

 

템플릿은 다 봤네요 

 

다음은 Controls 입니다

 

 

 

Controls 

https://docs.unity3d.com/Manual/UIE-ElementRef.html

https://docs.unity3d.com/ScriptReference/UIElements.BaseField_1.html

Element Function Namespace Permitted child elements (허용되는 자식 요소) Attributes
BaseField<T> 모든 필드의 추상 기본 클래스입니다. UnityEngine.UIElements None BindableElement의 모든 속성

focus-index, 
focusable,
label


focus-index : 기본 값 0 
focusable : 기본값 true 
label: 필드와 연결된 레이블의 텍스트

https://docs.unity3d.com/Packages/com.unity.ui@1.0/api/UnityEngine.UIElements.BaseField-1.html

 

 


 

 

Controls 

https://docs.unity3d.com/ScriptReference/UIElements.BaseFieldTraits_2.html

Element Function Namespace Permitted child elements (허용되는 자식 요소) Attributes
BaseFieldTraits<ValueType, UxmlType>   UnityEngine.UIElements None All attributes of BaseField<ValueType>

value

value: ValueType 유형의 필드 기본 값

 

 


 

 

Controls 

 

Element Function Namespace Permitted child elements (허용되는 자식 요소) Attributes
Button 표준 푸시 버튼입니다. UnityEngine.UIElements None TextElement의 모든 속성
delay,
interval

delay: 요소가 작업을 실행하기 전의 초기 지연(밀리초)입니다. 기본값은 0입니다.
interval: 각 작업을 반복하는 간격(밀리초)입니다. 기본값은 0입니다.

 

실습 하기 

 

위에서 작성한 MyWindow에 Button 컨트롤을 적용해봅시다 

<?xml version="1.0" encoding="utf-8"?>
<engine:UXML
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:engine="UnityEngine.UIElements"
    xmlns:editor="UnityEditor.UIElements"
    xsi:noNamespaceSchemaLocation="../../UIElementsSchema/UIElements.xsd"
>
  
  <engine:Template src="/Assets/Editor/Template.uxml" name="Template"/>
  <engine:Instance name="player1" template="Template">
    <AttributeOverrides element-name="player-name-label" text="Alice" />
  </engine:Instance>
  <engine:Button text="테스트 버튼"></engine:Button>
  
</engine:UXML>

 

이렇게 작성해도 됩니다 

 <engine:Button text="테스트 버튼"/>

속성은 TextElement의 모든 속성을 사용가능하기 때문에 

https://docs.unity3d.com/ScriptReference/UIElements.TextElement.html

https://docs.unity3d.com/Packages/com.unity.ui@1.0/api/UnityEngine.UIElements.Button.html

문서를 참고해가면서 필요한 속성을 넣으면 될듯 하네요 

 

 

 

[추가]

버튼 눌러 로그 출력 

<?xml version="1.0" encoding="utf-8"?>
<UXML xmlns="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements">
  <Button text="UXML Button" name="the-uxml-button" />
</UXML>
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor.UIElements;
using System;

public class TestWindow : EditorWindow
{
    [MenuItem("Window/UI Toolkit/TestWindow")]
    public static void ShowExample()
    {
        TestWindow wnd = GetWindow<TestWindow>();
        wnd.titleContent = new GUIContent("TestWindow");
    }

    public void CreateGUI()
    {
        // Each editor window contains a root VisualElement object
        VisualElement root = rootVisualElement;

        // VisualElements objects can contain other VisualElement following a tree hierarchy.
        VisualElement label = new Label("Hello World! From C#");
        root.Add(label);

        // Import UXML
        var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Editor/TestWindow.uxml");
        VisualElement container = visualTree.Instantiate();
        root.Add(container);

        // 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/Editor/TestWindow.uss");
        //VisualElement labelWithStyle = new Label("Hello World! With Style");
        //labelWithStyle.styleSheets.Add(styleSheet);
        //root.Add(labelWithStyle);

        // Action to perform when button is pressed.
        // Toggles the text on all buttons in 'container'.
        Action action = () =>
        {
            container.Query<Button>().ForEach((button) =>
            {
                //button.text = button.text.EndsWith("Button") ? "Button (Clicked)" : "Button";
                //Debug.Log("click");
            });
        };

        // Get a reference to the Button from UXML and assign it its action.
        var uxmlButton = container.Q<Button>("the-uxml-button");
        uxmlButton.RegisterCallback<MouseUpEvent>((evt) => action());

        // Create a new Button with an action and give it a style class.
        var csharpButton = new Button(()=> {
            Debug.Log("click c# button");
        }) { text = "C# Button" };

        csharpButton.AddToClassList("some-styled-button");
        container.Add(csharpButton);
    }
}


 

 

 

Controls 

https://docs.unity3d.com/Packages/com.unity.ui@1.0/api/UnityEngine.UIElements.RepeatButton.html

Element Function Namespace Permitted child elements (허용되는 자식 요소) Attributes
RepeatButton 누르고 있는 동안 동작을 반복적으로 실행하는 버튼입니다. UnityEngine.UIElements None TextElement의 모든 속성
delay,
interval

delay: 요소가 작업을 실행하기 전의 초기 지연(밀리초)입니다. 기본값은 0입니다.
interval: 각 작업을 반복하는 간격(밀리초)입니다. 기본값은 0입니다.

 

 

누르고있는 동안 동작을 반복적으로 실행 하는 버튼이라..

일단 실습 해봅니다 

<engine:RepeatButton text="Repeat Button"/>

왜 그냥 텍스트만 출력되는것일까..

 

IMGui 로 테스트 해봤습니다 

using UnityEngine;

public class Test : MonoBehaviour
{
    public Texture btnTexture;

    void OnGUI()
    {
        if (!btnTexture)
        {
            Debug.LogError("Please assign a texture on the inspector");
            return;
        }

        if (GUI.RepeatButton(new Rect(10, 10, 50, 50), btnTexture))
            Debug.Log("Clicked the button with an image");

        if (GUI.RepeatButton(new Rect(10, 70, 50, 30), "Click"))
            Debug.Log("Clicked the button with text");
    }
}

 

누르고 있으니깐 계속 출력 되는군요 

근데 버튼 모양이 보여야 되는거 아닌가 싶은데...

 

일단 스타일을 사용해서  width, height그리고 background-color로 영역을 확인해봤습니다 

<engine:RepeatButton text="Repeat Button" style="border-color:red; width:auto; height:auto; background-color: red;">
</engine:RepeatButton>

 

 

 

다음과 같이 Debugger를 사용해도 됩니다 

일단 눌러서 이벤트 받고 출력할라면 c#코드에서 처리 해야 할것 같음으로 버튼쪽은 일단 여기까지 보고 다음에 다시 살펴 보도록 해요 

 


 

길어지는거 같아 끊고 다음 포스팅으로 이어서 할게요 ~

 

다음시간에는 Toggle부터 살펴 보겠습니다 

https://docs.unity3d.com/Manual/UIE-ElementRef.html

https://docs.unity3d.com/Packages/com.unity.ui@1.0/api/UnityEngine.UIElements.Toggle.html

 

 

 

 

참고

 

https://nforbidden-fruit.tistory.com/44

https://blog.unity.com/kr/technology/whats-new-with-uielements-in-2019-1

https://docs.unity3d.com/kr/2018.4/Manual/UIE-UXML.html

https://docs.unity3d.com/kr/2019.4/Manual/UIE-WritingUXMLTemplate.html

 

반응형

'Unity3D' 카테고리의 다른 글

Day - 08. UI Toolkit 살펴 보기  (0) 2021.11.05
Day - 07. UI Toolkit 살펴 보기  (0) 2021.11.05
ngui joystick  (0) 2021.11.04
Day - 05. UI Toolkit 살펴 보기  (0) 2021.11.03
Day - 04. UI Toolkit 살펴 보기  (0) 2021.11.03
: