Get a Gradient from a Property

Has anyone worked out how to get a Gradient value from a Property in an editor script?

gradientProp = serializedObject.FindProperty("gradient");

Gradient gradient = gradientProp. ??

Bizarre. It exists, but it’s marked internal (line 876):

Try using reflection to access it:

PropertyInfo propertyInfo = typeof(SerializedProperty).GetProperty("gradientValue", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

Debug.Log(propertyInfo);

if(propertyInfo == null)
   return null;

Gradient gradient = propertyInfo.GetValue(gradientProp, null) as Gradient;

Debug.Log(gradient);

Remember using System.Reflection at the top. Let me know if it works, I typed it here.

1 Like

Seems to work. Thanks a lot.

For anyone else, here is my helper method based on the above.

/// <summary>
/// Get a Gradient from a SerializedProperty of a Gradient
/// </summary>
/// <param name="gradientProperty"></param>
/// <returns></returns>
public static Gradient GetGradient(SerializedProperty gradientProperty)
{
    System.Reflection.PropertyInfo propertyInfo = typeof(SerializedProperty).GetProperty("gradientValue", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

    if (propertyInfo == null) { return null; }
    else { return propertyInfo.GetValue(gradientProperty, null) as Gradient; }
}
3 Likes