Search Unity

Apply two CustomAttributes on one member

Discussion in 'Scripting' started by DaCookie, Nov 25, 2015.

  1. DaCookie

    DaCookie

    Joined:
    Nov 4, 2014
    Posts:
    44
    Hi everybody.

    I made two useful Custom Attributes : Min and Max. They require one parameter, an int or a float, and respectively prevent a class member value to be less or more than the given parameter.

    In my script, I can do this :

    Code (CSharp):
    1. [SerializeField, Min(0.0f)]
    2. private float m_TestValue = 0.0f;
    3.  
    4. [SerializeField, Max(2.0f)]
    5. private float m_TestValue2 = 0.0f;
    I can make a member Serialized AND use the Min or Max attribute.
    But I can't do this :

    [SerializeField, Min(0.0f), Max(2.0f)]
    private float m_TestValue3 = 0.0f;

    Only the first CustomAttribute (Min, in this example) will be used. But with the Unity attributes I can use at the same time SerializeField and HideInInspector for a member.

    Why I can't use more than one Custom Attribute on a member ? And how I can make it possible ?

    Thanks for your answers ;)
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,532
    I'm assuming Min and Max are custom attributes that are dealt with by PropertyDrawer.

    You can only have ONE PropertyDrawer affiliated attribute on a field. And if the type of that field uses a PropertyDrawer, only one is used.

    This is just the way that PropertyDrawers work.

    SerializeField is not a PropertyDrawer attribute.
    Nor is Tooltip, Header, and a few other unity specific attributes. And of course any .Net attributes aren't either.

    I did not like this myself, so I wrote my own custom editor to deal with this... but it is NOT trivial.

    You can see it here:
    https://github.com/lordofduct/spacepuppy-unity-framework/tree/master/SpacepuppyBaseEditor

    Editor entry point:
    https://github.com/lordofduct/space.../blob/master/SpacepuppyBaseEditor/SPEditor.cs

    That references around a lot to several classes to work correctly, and requires reflecting out a lot of internal classes from Unity themselves.

    And even with it, there are ramifications to stacking PropertyDrawers... only drawers that logically work with one another can stack.
     
  3. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,532
    Oh, and of course... unity has a 'Range' attribute that does a 'MinMax' type thing.

    Code (csharp):
    1.  
    2. [SerializeField, Range(0.0f, 2.0f)]
    3. private float m_TestValue = 0.0f;
    4.  
     
    Kiwasi likes this.
  4. DaCookie

    DaCookie

    Joined:
    Nov 4, 2014
    Posts:
    44
    I know the Range Attribute. Use both Min and Max is only for my example. But use them separately is better than a Range. If you make a Range(0.0f, Mathf.Infinity), you'll have a useless slider.

    Thanks for your answer, I'll check your scripts later ;)