Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Property.GetValue() causes NullReferenceException

Discussion in 'Scripting' started by JWLewis777, May 19, 2019.

  1. JWLewis777

    JWLewis777

    Joined:
    May 17, 2015
    Posts:
    64
    Holy smokes!

    I have an Item class with 4 properties. IName, IDescription, IType, ICategory.
    When I try to use reflection to iterate through the properties and Log the names and values, I get a NullReferenceException...

    Code (CSharp):
    1.  
    2. foreach(PropertyInfo property in item.GetType().GetProperties()){
    3.      If(property != null){
    4.           if(property.Name != null){
    5.                if(property.GetValue(item,null) != null){
    6.                      Debug.Log("Item: "+property.Name+", Value: "+property.GetValue(item,null));
    7.                }
    8.           }
    9.      }
    10. }
    11.  
    The error says the if line with GetValue is throwing the NullReferenceException error.

    thanks for any help!
     
  2. JWLewis777

    JWLewis777

    Joined:
    May 17, 2015
    Posts:
    64
    Well I see part of the problem...

    If I just log out the property.Name, I am getting property names for things such as
    useGUILayout
    runInEditMode
    enabled
    plus about 20 other properties I really didn't want.

    Any ideas on how to only return my defined properties?

    Thanks!
     
  3. JWLewis777

    JWLewis777

    Joined:
    May 17, 2015
    Posts:
    64
    Ok, it seemed part of the problem was that in my Item, some of the ItemName properties were null due to a typo in my JSON file.

    The other problem was that GetValue() returns all the properties of an object. In total there were 31 properties on my Item object which derived from MonoBehaviour.

    This is how I changed things...
    Code (CSharp):
    1.  
    2. foreach(PropertyInfo property in item.GetType().GetProperties(BindingFlags.Instance|BindingFlags.Public|BindingFlags.DeclaredOnly)){
    3.      If(property != null){
    4.           if(property.Name != null){
    5.                if(property.GetValue(item,null) != null){
    6.                      Debug.Log("Item: "+property.Name+", Value: "+property.GetValue(item,null));
    7.                }
    8.           }
    9.      }
    10. }
    Adding the BindingFlags.Declared only to the the GetProperties() method was the big fixer!
    (I found it here... BigFix)

    Wheew, that took me awhile to find, at least 50 searches and over 8 hours, hehehe.

    On to the next one!
    :)