如何在OnClick编辑器中添加下拉菜单?

时间:2019-05-29 04:48:31

标签: c# unity3d

我正在寻找一种将下拉框添加到检查器中的OnClick编辑器的方法(如下图所示)

Dropdown here

我希望下拉列表由自定义枚举填充。

这完全有可能吗?还是我需要找到另一种方式来做到这一点?

目标:
拥有一个音频剪辑枚举,并且无需检查代码就可以将所有剪辑都分配给检查员的按钮。

3 个答案:

答案 0 :(得分:0)

假设您知道编辑器和C#脚本之间的接口,我将简单地使用它们:

public static bool DropdownButton(GUIContent content, FocusType focusType, params GUILayoutOption[] options);

更多信息可以在这里找到:https://docs.unity3d.com/ScriptReference/EditorGUILayout.DropdownButton.html

答案 1 :(得分:0)

我看不到您的脚本,但是您可以使用EditorGUILayout.Popup

var options = new GUIContent[]
{
    new GUIContent("Otpion A"),
    new GUIContent("Option B"),
    new GUIContent("Option C")
    // ...
};

// whereever you get your current option from
currentlySelected = EditorGUILayout.Popup(currentlySelected, options);

enter image description here

如您所见,它也将您的错别字考虑在内:P


对于嵌套项目,只需使用/字符将其附加:

var options = new GUIContent[]
{
    new GUIContent("Option A/First Entry"),
    new GUIContent("Option A/Second Entry"),
    new GUIContent("Option A/Third Entry"),
    new GUIContent("Option B/First Entry"),
    new GUIContent("Option B/Second Entry"),
    new GUIContent("Option C/First Entry"),
    new GUIContent("Option C/Second Entry"),

    new GUIContent("Option C/Third Entry/And even one more level"),
    new GUIContent("Option C/Third Entry/With two options"),

    // ...
};

// whereever you get your current option from
currentlySelected = EditorGUILayout.Popup(currentlySelected, options);

enter image description here

答案 2 :(得分:0)

当前不支持它,并且自己编写代码也不那么容易。这将需要对UnityEventDrawerUnityEventBase的源代码进行深入的研究,并需要重现整个UnityEventDrawersource is avalable though ...


但是有一个非常简单的解决方法(至少如果每个Button都只能播放一个声音)

有一个单独的组件,如

[RequireComponent(typeof(Button))]
public class PlayASound : MonoBehaviour
{
    // reference via inspector
    [SerializeField] private AudioSelector _audioSelector;

    // your enum type here
    public AudioMessageType MessageType;

    public void Play()
    {
        _audioSelector.PublishAudioMesssage(MessageType);
    }

    private Button _button;

    private void Awake()
    {
         _button = GetComponent<Button>();

        if (!_button)
        {
            Debug.LogError("No Button found on this GameObject!", this);
            return;
        }

        _button.onClick.AddListener(Play);
    }

    // Just to to be sure
    // usually the button should be destroyed along with this component
    // anyway ... but you never know ;)
    private void OnDestroy()
    {
        _button.onClick.RemoveListener(Play);
    }
}

将其作为Button组件附加到相同 GameObject,然后在其中选择相应的枚举值,完成。 onClick的侦听器不会出现在检查器中,而是在运行时添加。

如果您希望手动添加它(有时我希望使其可见),则只需删除AwakeOnDestroy,然后像往常一样手动将其拖入并选择Play方法。