简单记录一下使用uitoolkit的时候用到的一些东西,都是使用中用到的,不一定全,留个记录备查
1.自定义控件
在制作自定义控件时,有需要根据控件的大小决定子级元素的数量个数间距等的,对于控件的 size 是动态变更的控件而言,可以注册 GeometryChangedEvent 事件, GeometryChangedEvent 中 的newRect 包含了控件的大小信息.
public class CustomControl : VisualElement
{
public CustomControl()
{
RegisterCallBack<GeometryChangedEvent>(OnGeometryChanged);
}
private void OnGeometryChanged(GeometryChangedEvent evt)
{
}
}
2.自定义控件属性
自定义控件属性,即可以在uibuilder的inspector中显示的自定义数据,这个数据需要在自定义的空间中声明对应的属性访问器,属性的名字和UxmlAttributeDescription中name的名称要保持一致,不能以_开头,在name中可以使用-来连接,使用-连接的字符,属性名不需要包含-字符,例如
private bool lineWidth{get;set}
UxmlBoolAttributeDescription lineWidthAttribute = new UxmlBoolAttributeDescription(){name = "lineWidth",defaultValue = false};
UxmlBoolAttributeDescription lineWidthAttribute = new UxmlBoolAttributeDescription(){name = "line-Width",defaultValue = false};
上面两种都是可以的.
3.自定义绘制图形(VectorAPI)
对于自定义的控件可以进行自定义绘制,要完成自定义绘制,需要为 generateVisualContent 指定回调.控件绘制需要的时候(如初次加载,布局变更,手动标记MarkDirtyRepaint)等情况的时候自动调用,参数MeshGenerationContext 中包含了自定绘制的主要工具Painter2D,详情可查
4.自定义属性描述器
unity默认的属性描述器有限,可以自己添加自己的属性描述器, 属性描述器需要继承自TypedUxmlAttributeDescription<T>,最主要的部分是完成GetValueFormBag(IUXMLAttributes bag, CreationContext cc)的函数实现, bag中有函数TryGetAttributeValue,通过属性名称获取属性的数据,获取到的数据是一个string类型,需要自己完成string到自定义类型的转换,在获取失败的时候,一般选择返回设定的默认值,如:
public class UxmlVector2AttributeDescription : TypedUxmlAttributeDescription<Vector2>
{
public UxmlVector2AttributeDescription(){}
public override Vector2 GetValueFromBag(IUxmlAttributes bag, CreationContext cc)
{
string bagContent = string.Empty;
if(bag.TryGetAttributeValue(name,out bagContent)
{
return Vector2.Prase(bagContent);
}
return defaultValue;
}
}
- VisualeElement持续调用
VisualeElement并没有Update或者FixedUpdate的方法来完成没帧的调用,如果需要在每帧进行更新或者固定间隔多少时间进行更新做持续不断的操作,诸如为VisualeElement制作动画效果等操作,可以借用VisualeElement的schedule来进行.
public class CustomController : VisualElement
{
public CustomController()
{
schedule.Execue(Function1).Every(5);
schedule.Execue(Function2).Until(()=> false);
}
private void Function1()
{
Debug.Log("A");
}
private void Function2(TimerState ts)
{
Debug.Log("B");
}
}
两种调用都是可行的,对于Function1来说,间隔5毫秒调用一次, 对于Function2来说,根据设定的条件(()=>flase)来确定调动,个人觉得比较反直觉的是,flase一直调用,true不调用
网友评论