【问题标题】:Unity UxmlAttributeDescription not setting values (resetting values)unity UxmlAttributeDescription 未设置值(重置值)
【发布时间】:2022-11-04 20:57:45
【问题描述】:

我正在为我的 UI 使用 UI Builder,并且正在创建一些自定义控件。我已经设法制作了一个可以正常工作的自定义控件。但是第二个有一些我无法理解的问题。

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

附加信息: 当我使用 UxmlIntAttributeDescription 类时,第一次出现问题。我有一个带有 UxmlStringAttributeDescription 和 UxmlIntAttributeDescription 的类。我能够设置字符串属性,但不能设置 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);
    }
}

【问题讨论】:

    标签: c# unity3d ui-toolkit


    【解决方案1】:

    • AttributeDescription 的名称应以 Attr 后缀结尾
    • 相应的公共{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);
            }
        }
    }
    

    【讨论】:

    • 谢谢,我需要做的就是将 private string _status; 更改为 private string status { get; set; } 。似乎变量不以_开头也很重要。但是不需要Attr 后缀。也许那已经改变了。
    • 这是有道理的。我只知道这一点,因为去年有人在论坛上提到了这一点。令人惊讶的是,这个文档页面甚至从未提到序列化系统需要任何东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多