Home > Back-end >  Is it possible to create an attribute that encapsulates a group of fields
Is it possible to create an attribute that encapsulates a group of fields

Time:06-22

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.

CodePudding user response:

There are a couple of built-in classes that you can use to group attributes visually in the inspector, such as Example usage of Space and Header

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.

CodePudding user response:

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].

[Serializable]
public class EncapsulatedProperties
{
    public string _name;
    public BlockType _blockType;
    public Sprite _sprite;
    public float _happinessMod, _pollutionMod;
}

public class OriginalClass
{
    [SerializeField]
    private EncapsulatedProperties props;
}

Only do so, however, if this way of Encapsulation makes sense within the scope of your unity project.

  • Related