Unity UI Toolkit学习笔记-C# 中创建自定义ui

参考1
参考2

🥡继承VisualElement

所有ui 元素都需要继承自VisualElement

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

public class MyElement : VisualElement
{
    
}

🌮定义UxmlFactory 暴露UI

为了暴露自定义的ui 元素 需要定义UxmlFactory

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

public class MyElement : VisualElement
{
    public new class UxmlFactory : UxmlFactory<MyElement,UxmlTraits> { }
}

添加好后就可以在UIBuilder > Library > Project >Custom Controls(C#)中看到自己定义的ui元素了
在这里插入图片描述

🥠命名空间组织结构

可以通过命名空间来组织ui结构
在这里插入图片描述

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace ZYF.UIEle
{
    public class MyElement : VisualElement
    {
        public new class UxmlFactory : UxmlFactory<MyElement, UxmlTraits> { }
    }
}

🍥 添加自定义属性

在这里插入图片描述

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace ZYF.UIEle
{
    public class MyElement : VisualElement
    {
        public new class UxmlFactory : UxmlFactory<MyElement, UxmlTraits> { }

        public new class UxmlTraits : VisualElement.UxmlTraits {

            UxmlStringAttributeDescription m_Str = new UxmlStringAttributeDescription { 
                name = "string-attr",
                defaultValue = "str属性"
            };

            UxmlIntAttributeDescription m_Int = new UxmlIntAttributeDescription {
                name ="int-attr",
                defaultValue=2
            };

            public override IEnumerable<UxmlChildElementDescription> uxmlChildElementsDescription
            {
                get { yield break; }
            }
            public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
            {
                base.Init(ve, bag, cc);
                var ate = ve as MyElement;

                ate.stringAttr = m_Str.GetValueFromBag(bag:bag,cc:cc);
                ate.intAttr = m_Int.GetValueFromBag(bag:bag,cc:cc);
            }

        }
        public string stringAttr { get; set; }
        public int intAttr { get; set; }
    }
}

需要注意的是: C# 属性名字要根据Uxml*AttributeDescription中的name 来设置,首先去掉破折号,然后按驼峰命名法把它们组合一起;
在这里插入图片描述

🚨注意

当前的UIBuilder 不支持自定义ui元素的自定义Inspector

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

牙膏上的小苏打2333

哟,哟,切克闹,煎饼果子来一套

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值