Unity 的自定义检查器枚举字段有条件地允许某些枚举值而不是其他枚举值

Unity's Custom Inspector Enum field to conditionally allow some enum values and not others

我有两个枚举。

第一个是PrimaryColor,可以是"Red, Yellow, or Blue"

第二个是TertiaryColor,可以是"Red, Magenta, Purple, Violet, Blue, etc"

我希望我的自定义检查器仅显示一个可能值的子集,以便根据第一个枚举的值为第二个枚举选择。所以如果它是蓝色的,我希望用户能够选择 "purple, violet, teal, magenta, blue," 而不是 red/orange/etc.

我发现自定义检查器 "checkEnabled" 中有一个选项听起来很适合这个:

https://docs.unity3d.com/ScriptReference/EditorGUILayout.EnumPopup.html

但是我在尝试使用该字段时无法编译它。

谁能给我一个例子,说明如何使用 EnumPopUp 的 checkEnabled 字段来执行此操作?我可以让 enumPopup 方法工作得很好,基本参数传递给它一个字符串和枚举,但是当我尝试传递给它自定义函数方法时,它说所有参数都不能转换成 GUIlayoutoptions。

//The variation of the method I am attempting to run
public static Enum EnumPopup(GUIContent label, Enum selected, Func<Enum,bool> checkEnabled, 
bool includeObsolete, params GUILayoutOption[] options);
MyColor myColor = (MyColor)target;
Func<TertiaryColorEnum, bool> showEnumValue = ShowEnumValue;
GUIContent label = new GUIContent("Color");

//this call gives me a red line under every paramater even though they should all be what it needs
myColor.tertiaryColor = (TertiaryColorEnum)EditorGUILayout.EnumPopup(label, myColor.tertiaryColor,
showEnumValue, true);

//these ones work just fine (other parameter sets for the method)
myColor.tertiaryColor = (TertiaryColorEnum)EditorGUILayout.EnumPopup(myColor.tertiaryColor);
myColor.tertiaryColor = (TertiaryColorEnum)EditorGUILayout.EnumPopup("hi", myColor.tertiaryColor);
myColor.tertiaryColor = (TertiaryColorEnum)EditorGUILayout.EnumPopup(label, myColor.tertiaryColor);


// my custom function
public static bool ShowEnumValue(TertiaryColorEnum tertiaryColorEnum)
{  
    if(myColor.primaryColor == PrimaryColorEnum.Red)
    {
       if(tertiaryColorEnum == TertiaryColorEnum.Purple)
           return false;
       else
           return true;
    }
}

我最好的猜测是我对它想要的 Func 参数做错了,但我不知道如何做。任何帮助或想法将不胜感激!

您的 ShowEnumValue 必须接受 Enum。然后,您可以在函数内将 Enum 转换为 TertiaryColorEnum 并对其进行操作,但否则您的函数与 Func< Enum, bool> 原型,因此编译器将调用匹配到下一个适当的原型:

public static Enum EnumPopup(string label, Enum selected, params GUILayoutOption[] options); 

这就像如果你有一个接受特定 type/class(例如动物)的代表,而你试图给它一个接受派生的 class(例如狮子)的代表 - 代表期望也可以处理鳄鱼的功能!

Some reading on the topic of Covariance and Contravariance if you're interested.