【问题标题】:How to add dropdown in OnClick editor?如何在 OnClick 编辑器中添加下拉菜单?
【发布时间】:2019-05-29 04:48:30
【问题描述】:

我正在寻找一种在检查器中向 OnClick 编辑器添加下拉框的方法(在下图中圈出)

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

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

目标:
拥有一个音频剪辑的枚举,并且能够将剪辑分配给一个按钮,所有这些都来自检查器,而无需进入代码。

【问题讨论】:

标签: c# unity3d


【解决方案1】:

假设您知道编辑器和 C# 脚本之间的交互方式,我会简单地使用:

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

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

【讨论】:

    【解决方案2】:

    目前不支持,而且自己编写代码也不是那么容易。这需要对UnityEventDrawerUnityEventBase 的源代码进行一些深入的破解,并复制整个UnityEventDrawer (source 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 的监听器不会出现在 Inspector 中,但会在运行时添加。

    如果您喜欢手动添加它(我有时更喜欢让它可见),那么只需删除 AwakeOnDestroy 并像往常一样手动将其拖入并选择 Play 方法。

    【讨论】:

      猜你喜欢
      • 2012-02-24
      • 1970-01-01
      • 2011-01-09
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-22
      相关资源
      最近更新 更多