是否可以创建一个封装一组字段的属性
在Unity中,您可以通过公开或使用属性[SerializeField]将字段暴露给编辑器。显然,SerializeField在可访问性方面更安全,但是当您有一堆需要暴露的字段时,它看起来很混乱。请参阅此处:
//editor exposed fields
[SerializeField]
string _name;
[SerializeField]
BlockType _blockType;
[SerializeField]
Sprite _sprite;
[SerializeField]
float _happinessMod, _pollutionMod;
但是我想做的是创建两个封装一组字段的属性,例如:
//editor exposed fields
[SerializeFieldBlock]
string _name;
BlockType _blockType;
Sprite _sprite;
float _happinessMod, _pollutionMod;
[SerializeBlockEnd]
正如您可以在第二个示例中看到的代码远比第一个示例更可读性。这可能吗?我以前从未编码过一个属性。
In unity you can expose fields to the editor by making them public or with the attribute [SerializeField]. Obviously SerializeField is safer in terms of accessibility, but it looks quite messy when you have a bunch of fields that need to be exposed. See here:
//editor exposed fields
[SerializeField]
string _name;
[SerializeField]
BlockType _blockType;
[SerializeField]
Sprite _sprite;
[SerializeField]
float _happinessMod, _pollutionMod;
but what I would like to do is create two attributes that encapsulate a group of fields, like this:
//editor exposed fields
[SerializeFieldBlock]
string _name;
BlockType _blockType;
Sprite _sprite;
float _happinessMod, _pollutionMod;
[SerializeBlockEnd]
As you can see the code in the second example is far more readable than the first. Is this possible? I've never coded an attribute before.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用几个内置类来视觉属性,例如 spaceattribute 和 headerattribute 。请参阅其中的示例用法:
这将在以下结果中产生:
如果您有进一步的特定需求,则可以通过扩展
decorpordordrawer
来创建自己的装饰图。 Unity Documentation 提供了一个很好的解释,可以很好地解释您如何使用它。There are a couple of built-in classes that you can use to group attributes visually in the inspector, such as SpaceAttribute and HeaderAttribute. See an example usage of them:
This results in the following:
If you have further specific needs, you can create your own decorator drawers by extending
DecoratorDrawer
. The Unity documentation offers a good explanation about how you could use it.另一种解决方案可能是将您的所有字段都封装到单独的数据类中。只要您对对象有参考,所有这些属性都应公开访问。
可以将此类实例化并分配到原始类中的字段。为了将其所有属性公开到编辑器中,请将整个对象字段标记为
[serialized field]
。但是,只有这种封装方式在您的Unity项目范围内有意义。
An alternative solution might be to encapsulate all of your fields into a separate data class. All of these properties should be publicly accessible, as long as you have a reference to the object.
This class can be instantiated and assigned to a field in your original class. In order to expose all of its properties to the editor, mark the whole object field as
[SerializedField]
.Only do so, however, if this way of Encapsulation makes sense within the scope of your unity project.