Unity3D :创建具有两个属性的自定义控件

推荐:将NSDT场景编辑器加入你的3D工具链
3D工具集:NSDT简石数字孪生

创建具有两个属性的自定义控件

此示例演示如何创建具有两个属性的简单自定义控件。

示例概述

此示例创建一个使用两个属性调用的自定义控件,并将其公开给 UXML 和MyElement用户界面
建筑工人。此示例还演示如何将自定义控件添加到 UI 生成器中的 UI。

您可以在此 GitHub 存储库中找到此示例创建的已完成文件。

先决条件

本指南适用于熟悉 Unity、UI 工具包和 C# 脚本的开发人员。在开始之前,请熟悉以下内容:

  • 用户体验
  • 用户界面生成器

创建示例

若要在 C# 中创建新的自定义控件类,请从该类继承它。这允许您在 C# 中创建和使用此元素,但不会在 UXML 和 UI 生成器中自动公开它。要公开它,请定义派生自 .VisualElementUxmlTraitsInit()

  1. 使用任何模板创建 Unity 项目。
  2. 在该文件夹中,创建一个以以下内容命名的 C# 脚本:AssetsMyElement.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 生成器中将其打开。

5. 在 UI 生成器的“”部分中,选择“项目>自定义控件 (C#)”> MyElement

6. 将 MyElement 拖到“层次结构”窗口中。

7.要查看 MyElement 的自定义属性,请转到检查员
MyElement的窗口:

自定义控件的自定义属性

3D建模学习工作室整理翻译,转载请注明出处!

上一篇:Unity3D :使用切换创建条件 UI (mvrlink.com)

下一篇:Unity3D :创建滑动切换自定义控件 (mvrlink.com)

NSDT场景编辑器 | NSDT 数字孪生 | GLTF在线编辑器 | 3D模型在线转换 | UnrealSynth虚幻合成数据生成器 | 3D模型自动纹理化工具
2023 power by nsdt©鄂ICP备2023000829号