您当前的位置: 首页 >  unity
  • 4浏览

    0关注

    157博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

牙膏上的小苏打2333 发布时间:2022-09-05 15:05:44 ,浏览量:4

🔮在C# 中创建自定义ui
  • 🥡继承VisualElement
  • 🌮定义UxmlFactory 暴露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 { }
}

添加好后就可以在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 { }
    }
}

🍥 添加自定义属性

在这里插入图片描述

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

        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 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

关注
打赏
1664520285
查看更多评论
立即登录/注册

微信扫码登录

0.0491s