【Unity】Unity Editor禁止通过键盘删除GameObject
如果希望某个GameObject不可以通过键盘的Delete键进行删除,可以为这个GameObject实现一个自定义的编辑器扩展类,在扩展类中每帧检测Unity Editor的 Event ,如果当前的 Event 对应了Delete键事件,则将其标记为 Used ,这样Unity Editor便不再处理该 Event 。
下面的代码是一个简单的实现。将 DisableKeyboardDelete 脚本添加到GameObject上,即可阻止在 Hierarchy 中通过 Delete 键删除这个GameObject。如果Unity编辑器的 Gizmos 绘制功能没有被关闭,那么这个脚本也可以阻止在 Scene 视图中通过 Delete 键删除GameObject。
DisableKeyboardDelete:
using UnityEngine;
public class DisableKeyboardDelete : MonoBehaviour
{
// 这是个简单的方法,但是不能处理多选
//private void OnDrawGizmos()
//{
// var e = Event.current;
// if (e.keyCode == KeyCode.Delete)
// {
// //e.Use(); // will log warning
// e.type = EventType.Used;
// UnityEngine.Debug.Log($"This Object prohibits deletion by keyboard: {this}.", this);
// }
//}
#if UNITY_EDITOR
/// <summary>
/// 禁止在Hierarchy窗口中使用键盘删除GameObject,但是不能禁止在Hierarchy中通过右键菜单删除GameObject。
/// 如果启用了Gizmos绘制,那么此类也可以阻止在Scene窗口中通过键盘删除GameObject。
/// </summary>
[UnityEditor.CustomEditor(typeof(DisableKeyboardDelete), true), UnityEditor.CanEditMultipleObjects]
public class DisableKeyboardDeleteEditor : UnityEditor.Editor
{
private void OnEnable()
{
UnityEditor.EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyGUI;
}
private void OnDisable()
{
UnityEditor.EditorApplication.hierarchyWindowItemOnGUI -= OnHierarchyGUI;
}
// 禁止在Scene中通过键盘删除(注意:OnSceneGUI()仅在启用了Gizmos时才能被调用)
private void OnSceneGUI()
{
InterceptKeyboardDelete();
}
// 禁止在Hierarchy中通过键盘删除
private void OnHierarchyGUI(int instanceID, Rect selectionRect)
{
InterceptKeyboardDelete();
}
// 拦截键盘删除事件
private void InterceptKeyboardDelete()
{
var e = Event.current;
if (e.keyCode == KeyCode.Delete)
{
//e.Use(); // will log warning
e.type = EventType.Used;
UnityEngine.Debug.Log($"This Object prohibits deletion by keyboard: {target}.", target);
}
}
}
#endif
}
449




