Version: 2022.1
言語: 日本語
トグルを使って条件付き UI を作成する
スライドトグルカスタムコントロールの作成

2 つの属性を持つカスタムコントロールの作成

バージョン: 2021.3 以降

この例では、2 つの属性を持つ単純なカスタムコントロールの作成方法を説明します。

例の概要

この例では、2 つの属性を持つ MyElement というカスタムコントロールを作成し、UXML と UI Builder に公開します。この例では、UI Builder でカスタムコントロールを UI に追加する方法も説明します。

この例で作成するすべてのファイルは、GitHub リポジトリ にあります。

要件

このガイドは、Unity、UI Toolkit、および C# スクリプトに精通している開発者向けです。始める前に、以下を理解しておいてください。

例の作成

C# で新しいカスタムコントロールクラスを作成するには、VisualElement クラスを継承します。これにより、C# でこの要素を作成して使用することができますが、UXML や UI Builder では自動的に公開されません。公開するには、UxmlTraits から派生した trait クラスを定義し、Init() をオーバーライドします。

  1. 任意のテンプレートで Unity プロジェクトを作成します。

  2. Assets フォルダーに、以下の内容の C# スクリプトを作成し MyElement.cs と命名します。

    using UnityEngine;
    using UnityEngine.UIElements;
    
    class MyElement : VisualElement
    {
        public new class UxmlFactory : UxmlFactory<MyElement, UxmlTraits> { }
    
        // Add the two custom UXML attributes.
        public new class UxmlTraits : VisualElement.UxmlTraits
        {
            UxmlStringAttributeDescription m_String =
                new UxmlStringAttributeDescription { name = "my-string", defaultValue = "default_value" };
            UxmlIntAttributeDescription m_Int =
                new UxmlIntAttributeDescription { name = "my-int", defaultValue = 2 };
            
            public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
            {
                base.Init(ve, bag, cc);
                var ate = ve as MyElement;
    
                ate.myString = m_String.GetValueFromBag(bag, cc);
                ate.myInt = m_Int.GetValueFromBag(bag, cc);
            }
        }
        
        // Must expose your element class to a { get; set; } property that has the same name 
        // as the name you set in your UXML attribute description with the camel case format
        public string myString { get; set; }
        public int myInt { get; set; }
    }
    
  3. 任意の名前で UXML ファイルを作成します。

  4. UXML ファイルをダブルクリックして、UI Builder で開きます。

  5. UI Builder の Library セクションで、Project > Custom Controls (C#) > MyElement を選択します。

  6. MyElement を Hierarchy ウィンドウにドラッグします。

  7. MyElement カスタム属性を見るには、MyElementInspector ウィンドウに移動します。

カスタムコントロールのカスタム属性
カスタムコントロールのカスタム属性

その他の参考資料

トグルを使って条件付き UI を作成する
スライドトグルカスタムコントロールの作成