发送命令事件是为了允许 Unity 编辑器将顶级菜单操作及其等效的键盘快捷键转发到 Editor__ UI__(即用户界面,User Interface)让用户能够与您的应用程序进行交互。Unity 目前支持三种 UI 系统。更多信息
See in Glossary。
以下是可用的命令:
CopyCutPasteDeleteSoftDeleteDuplicateFrameSelectedFrameSelectedWithLockSelectAllFindFocusProjectWindow| 事件 | 描述 | 涓滴 | 冒泡 | 可取消 |
|---|---|---|---|---|
| ValidateCommandEvent | 编辑器在确定面板中的元素是否处理命令时,会发送此事件。 | ✔ | ✔ | ✔ |
| ExecuteCommandEvent | 当面板中的某一元素应执行命令时,编辑器会发送此事件。 | ✔ | ✔ | ✔ |
target:获得键盘焦点的元素。如果没有元素获得焦点,此值为 null。
commandName:用于验证或执行的命令。
ValidateCommandEvent 事件询问 EditorWindow 是否可以执行命令。例如,编辑器可以根据验证命令事件的结果启用或禁用菜单项。
要验证编辑器是否可以执行命令:
ValidateCommandEvent 的回调。commandName 属性。Event.StopPropogation() 方法。
ExecuteCommandEvent 事件要求 Editor 窗口执行命令。
即使此事件在验证事件之后,最佳做法仍是首先确保操作的可能性,不依赖先前的任何验证。
要响应命令:
ExecuteCommandEvent 的回调。commandName 属性。Event.StopPropogation() 方法,以便编辑器知道注释已被执行。以下示例使用命令事件支持在自定义 Editor 窗口中复制和粘贴。该示例将在自定义 Editor 窗口中显示水果列表。用户可以使用键盘快捷键复制和粘贴任何水果。
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();
}
}
}