簡體   English   中英

Unity 的自定義檢查器枚舉字段有條件地允許某些枚舉值而不是其他值

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

我有兩個枚舉。

第一個是 PrimaryColor,可以是“Red、Yellow 或 Blue”

第二個是 TertiaryColor,可以是“紅色、品紅色、紫色、紫羅蘭色、藍色等”

我希望我的自定義檢查器僅顯示可能值的子集,以根據第一個枚舉的值為第二個枚舉選擇。 因此,如果它是藍色,我希望用戶能夠從“紫色、紫羅蘭色、藍綠色、洋紅色、藍色”中進行選擇,但不能選擇紅色/橙色/等。

我發現自定義檢查器“checkEnabled”中有一個選項聽起來非常適合:

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

但是,在嘗試使用此字段時,我無法編譯它。

誰能給我一個關於如何使用 EnumPopUp 的 checkEnabled 字段來執行此操作的示例? 我可以讓 enumPopup 方法與傳遞字符串和枚舉的基本參數一起正常工作,但是當我嘗試將自定義 function 方法傳遞給它時,它說所有參數都不能轉換為 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 轉換為 function 中的TertiaryColorEnum並對其進行操作,否則您的 function 與Func< Enum, bool>原型不匹配,因此編譯器會將調用匹配到下一個適當的原型:

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

這就像如果您有一個接受特定類型/類(例如動物)的代表,並且您試圖給它一個接受派生的 class(例如 Lion)的代表 - 代表期望 function 也可以處理鱷魚!

如果您有興趣,可以閱讀一些關於協方差和逆變的主題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM