所有ui 元素都需要继承自VisualElement
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class MyElement : VisualElement
{
}
为了暴露自定义的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