包含此页的版本:
不含此页的版本:
发送命令事件以允许 Unity 编辑器将顶级菜单作及其等效键盘快捷键转发到编辑器 UI。
以下是可用的命令:
CopyCutPasteDeleteDeselectAllSoftDeleteDuplicateFrameSelectedFrameSelectedWithLockSelectAllFindFocusProjectWindow| 事件 | 描述 | 涓涓细流 | 气泡升起 | 可取消 |
|---|---|---|---|---|
| ValidateCommandEvent | 编辑器在确定面板中的元素是否处理命令时发送此事件。 | ✔ | ✔ | ✔ |
| ExecuteCommand事件 | 当面板中的元素执行命令时,编辑器会发送此事件。 | ✔ | ✔ | ✔ |
target:具有键盘焦点的元素。此值为null如果没有元素有焦点。
commandName:要验证或执行的命令。
这ValidateCommandEvent事件询问 EditorWindow 是否可以执行命令。例如,编辑器可以根据验证命令事件的结果启用或禁用菜单项。
要验证编辑器是否可以执行命令,请执行以下作:
ValidateCommandEvent.commandName事件的属性。Event.StopPropogation()如果可以执行命令,则对事件进行方法。这ExecuteCommandEvent事件要求编辑器窗口执行命令。
即使此事件发生在验证事件之后,最佳做法也是确保首先可以执行该作,而不受任何先前验证的影响。
要响应命令:
ExecuteCommandEvent.commandName事件的属性。Event.StopPropogation()方法,然后再执行命令的实际逻辑,所以编辑器知道注释已经执行了。以下示例使用命令事件来支持在自定义编辑器窗口中复制和粘贴。该示例在自定义编辑器窗口中显示水果列表。用户可以使用键盘快捷键复制和粘贴任何水果。
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
public class CopyPasteExample : EditorWindow
{
[MenuItem("Window/UI Toolkit Examples/CopyPasteExample")]
public static void Show()
{
GetWindow<CopyPasteExample>();
}
readonly List<string> fruits = new ()
{
"Banana",
"Apple",
"Lime",
"Orange"
};
ListView m_ListView;
public void CreateGUI()
{
Func<VisualElement> makeItem = () => new Label();
Action<VisualElement, int> bindItem = (e, i) => (e as Label).text = fruits[i];
m_ListView = new ListView();
m_ListView.makeItem = makeItem;
m_ListView.bindItem = bindItem;
m_ListView.itemsSource = fruits;
m_ListView.selectionType = SelectionType.Single;
m_ListView.RegisterCallback<ValidateCommandEvent>(OnValidateCommand);
m_ListView.RegisterCallback<ExecuteCommandEvent>(OnExecuteCommand);
rootVisualElement.Add(m_ListView);
}
void OnExecuteCommand(ExecuteCommandEvent evt)
{
if (evt.commandName == "Copy" && m_ListView.selectedIndices.Count() > 0)
{
EditorGUIUtility.systemCopyBuffer = fruits[m_ListView.selectedIndex];
evt.StopPropagation();
}
else if (evt.commandName == "Paste" && !string.IsNullOrEmpty(EditorGUIUtility.systemCopyBuffer))
{
fruits.Add(EditorGUIUtility.systemCopyBuffer);
m_ListView.RefreshItems();
evt.StopPropagation();
}
}
void OnValidateCommand(ValidateCommandEvent evt)
{
if (evt.commandName == "Copy" && m_ListView.selectedIndices.Count() > 0)
{
evt.StopPropagation();
}
else if (evt.commandName == "Paste" && !string.IsNullOrEmpty(EditorGUIUtility.systemCopyBuffer))
{
evt.StopPropagation();
}
}
}