Search code examples
c#unity-game-engineunity-editor

Changing the Unity Color Gradient Inspector Field


I'm using Unity's color gradient property field in a custom inspector drawer like this:

SerializedProperty colorGradient = property.FindPropertyRelative("colorGradient");
EditorGUI.PropertyField(pos, colorGradient);

This initializes with no valid gradient being selected. I'd like to preload the first one in the project set before the user selects one from the stored set or creates a new one.

With other PropertyField types like IntSlider, it's simple to access its .intValue member for setting it directly. From the debugger, I can see a non-public .gradientValue member, but I don't see any relevant value member for the colorGradient type that is accessible to set directly from a script. Any ideas?


Solution

  • I want to set the default gradient to something other than a null instance that is a blank, white gradient.

    Since your field is serialized it will not be null (otherwise you would already get a NullReferenceException). It is rather simply the default value used by new Gradient().

    In order to have a default gradient in the Inspector you actually wouldn't need a special editor or property drawer. You only would need to assign some default values to it when you declare the field in your class:

    using UnityEngine;
    
    public class ExampleScript : MonoBehaviour
    {
        [SerializeField]
        private Gradient exampleGradient = new Gradient
        {
            alphaKeys = new[]
            {
                new GradientAlphaKey(0, 0f),
                new GradientAlphaKey(1, 1f)
            },
    
            colorKeys = new[]
            {
                new GradientColorKey(Color.red, 0f),
                new GradientColorKey(Color.cyan, 0.5f),
                new GradientColorKey(Color.green, 1f)
            }
        };
    }
    

    enter image description here