【问题标题】:Unity's Custom Inspector Enum field to conditionally allow some enum values and not othersUnity 的自定义检查器枚举字段有条件地允许某些枚举值而不是其他枚举值
【发布时间】:2019-10-23 18:44:54
【问题描述】:

我有两个枚举。

第一个是 PrimaryColor,可以是“红色、黄色或蓝色”

第二个是TertiaryColor,可以是“红、品红、紫、紫、蓝等”

我希望我的自定义检查器仅显示可能值的子集,以便根据第一个枚举的值为第二个枚举选择。因此,如果它是蓝色,我希望用户能够从“紫色、紫罗兰色、蓝绿色、洋红色、蓝色”中进行选择,但不能选择红色/橙色/等。

我发现自定义检查器“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 参数做错了,但我不知道怎么做。任何帮助或想法将不胜感激!

【问题讨论】:

    标签: c# function unity3d inspector


    【解决方案1】:

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

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

    这就像如果您有一个接受特定类型/类(例如 Animal)的委托,并且您试图给它一个接受派生类(例如 Lion)的委托 - 委托也需要一个可以处理鳄鱼的函数!

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

    【讨论】:

    • 非常感谢,不知道为什么我没有想到,将其更改为采用枚举并完美地投射它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    相关资源
    最近更新 更多