更改 Unity 颜色渐变检查器字段

Changing the Unity Color Gradient Inspector Field

我在自定义检查器抽屉中使用 Unity 的颜色渐变 属性 字段,如下所示:

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

这会在没有选择有效渐变的情况下进行初始化。我想在用户从存储的集合中选择一个或创建一个新的之前预加载项目集中的第一个。

对于其他 PropertyField 类型,如 IntSlider,直接访问它的 .intValue 成员来设置它很简单。从调试器中,我可以看到一个非 public .gradientValue 成员,但我没有看到任何可直接从脚本设置的 colorGradient 类型的相关值成员。有什么想法吗?

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

由于您的字段已序列化,因此它不会是 null(否则您已经得到 NullReferenceException)。它只是 new Gradient().

使用的默认值

为了在 Inspector 中使用默认渐变,您实际上不需要特殊的编辑器或 属性 抽屉。当您在 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)
        }
    };
}