Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Issue with Attribute.IsDefined

Discussion in 'Scripting' started by UserNobody, Oct 2, 2020.

  1. UserNobody

    UserNobody

    Joined:
    Oct 3, 2019
    Posts:
    144
    Hi,
    I am trying to check if a variable has a TextArea attribute, but even if it does it still returns false.
    What am I doing wrong here?

    Code (CSharp):
    1. public class Product
    2. {
    3.     [SerializeField] string ID;
    4.     [SerializeField] string Name;
    5.     [TextArea(4, 8)]
    6.     [SerializeField] string Description;
    7.     [SerializeField] double price;
    8. }
    9.  
    10. Product product;
    11.  
    12. public void GetProperties()
    13. {
    14.     PropertyInfo[] properties = product.GetType().GetProperties();
    15.     foreach (PropertyInfo property in properties)
    16.     {
    17.         Debug.Log(Attribute.IsDefined(property, typeof(TextAreaAttribute)));
    18.     }
    19. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,336
    I agree it does not seem to work, at least in Editor. Have you tried making a build?

    Based on the API it seems it should perhaps say true, but the example given by Microsoft docs gives ParameterArrayAttribute as an example, and then they apply it by using the keyword in the args declaration, rather than as a pure decorator, sort of muddying the water as compared with yours. Perhaps it's identical, I'm not enough of a C# weenie to know.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,336
    oh duh, it's a field, not a property. Use GetField and FieldInfo.

    Code (csharp):
    1.  
    2.         FieldInfo[] fields = product.GetType().GetFields();
    3.         foreach (FieldInfo field in fields)
    4.         {
    5.             var ggg = field.Name;
    6.             Debug.Log(ggg + " - " + Attribute.IsDefined(field, typeof(TextAreaAttribute)));
    7.         }
    8.  
    9.  
    Screen Shot 2020-10-02 at 12.19.27 PM.png
     
    Last edited: Oct 2, 2020
    UserNobody likes this.
  4. UserNobody

    UserNobody

    Joined:
    Oct 3, 2019
    Posts:
    144
    Yup I just figured it out as well :D Silly mistakes... Thanks anyways!
     
    Joe-Censored and Kurt-Dekker like this.