c# - unity UxmlAttributeDescription 不设置值(重置值)

标签 c# unity-game-engine ui-toolkit

我正在为我的 UI 使用 UI Builder,并创建一些自定义控件。我已经成功制作了一个运行完美的自定义控件。但第二个有一些我无法理解的问题。

问题: 我可以将自定义控件放入 UI 生成器中。从一开始,“status”属性就没有默认值,它只是空白。当我手动输入一个值并单击离开时,“状态”值将重置为空白。 在控制台中,我从构造函数收到消息“null”,这意味着我输入的值未设置。

附加信息: 当我使用 UxmlIntAttributeDescription 类时,问题首先出现。我有一个带有 UxmlStringAttributeDescription 和 UxmlIntAttributeDescription 的类。我可以设置 string 属性,但不能设置 int 属性。我不断简化我的代码,这样我就可以发布这个问题,然后甚至字符串属性也被破坏了。 我真的不知道我哪里搞砸了,希望有人能帮助我解决这个问题。

这是我的代码。其大部分复制自 https://docs.unity3d.com/Manual/UIE-UXML.html .

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

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

    public new class UxmlTraits : VisualElement.UxmlTraits {

        UxmlStringAttributeDescription m_status = new UxmlStringAttributeDescription { name = "status", defaultValue = "TestElementString" };
      
        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 TestElement;

            ate._status = m_status.GetValueFromBag(bag, cc);
        }
    }

    private string _status;
    
    public TestElement() {
        Debug.Log(_status);
    }
}

最佳答案


  • AttributeDescription 的名称应以 Attr 后缀结尾
  • 相应的公共(public) {get;set;} 属性必须存在且名称相同,但没有 Attr 后缀

否则序列化系统将无法使用此元素。

public class TestElement : VisualElement
{
    public string status { get; set; }
    public new class UxmlFactory : UxmlFactory<TestElement,UxmlTraits> {}
    public new class UxmlTraits : VisualElement.UxmlTraits
    {
        UxmlStringAttributeDescription statusAttr = new UxmlStringAttributeDescription { name = "status", defaultValue = "TestElementString" };
        public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
        {
            base.Init(ve, bag, cc);
            var ate = ve as TestElement;

            ate.status = statusAttr.GetValueFromBag(bag, cc);
        }
    }
}

关于c# - unity UxmlAttributeDescription 不设置值(重置值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73428682/

相关文章:

c# - Visual Studio 2012 代理需要授权

c# - 测试异步方法不会给出一致的结果

unity-game-engine - 如何在 Hololens 模拟器中测试 Air Tap 手势?

unity-game-engine - 如何获取瓦片 map 中瓦片的 x,y 坐标位置?

c# - 参数异常 : Getting control 1's position in a group with only 1 controls when doing repaint

c# - 有没有一种方法可以在运行时轻松地将数据绑定(bind)到UI

c# - .NET 项目的最佳开源项目托管站点

c# - 打开和关闭防病毒软件