unity ReorderableList鼠标右键回调
时间: 2023-07-12 18:32:31 浏览: 169
Unity扩展Hierachry的右键菜单
要在Unity的ReorderableList中实现鼠标右键回调,可以使用UnityEditor.GenericMenu类。首先,在ReorderableList的OnGUI函数中,检测是否有鼠标右键按下事件,如果有,则创建一个GenericMenu对象,并添加菜单项。然后,调用GenericMenu的ShowAsContext函数,以显示右键菜单。
以下是一个示例代码,用于在ReorderableList中实现鼠标右键回调:
```csharp
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
public class Example : EditorWindow
{
private ReorderableList list;
[MenuItem("Window/Example")]
private static void ShowWindow()
{
GetWindow<Example>("Example");
}
private void OnEnable()
{
list = new ReorderableList(serializedObject, serializedObject.FindProperty("list"), true, true, true, true);
list.drawElementCallback = (rect, index, isActive, isFocused) =>
{
var element = list.serializedProperty.GetArrayElementAtIndex(index);
rect.y += 2;
EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), element);
};
list.drawHeaderCallback = rect =>
{
EditorGUI.LabelField(rect, "List");
};
list.onAddCallback = list =>
{
var index = list.serializedProperty.arraySize;
list.serializedProperty.arraySize++;
list.index = index;
};
list.onRemoveCallback = list =>
{
if (EditorUtility.DisplayDialog("Delete item", "Are you sure?", "Yes", "No"))
{
ReorderableList.defaultBehaviours.DoRemoveButton(list);
}
};
list.onMouseUpCallback = list =>
{
if (Event.current.button == 1 && list.index >= 0 && list.index < list.serializedProperty.arraySize)
{
var menu = new GenericMenu();
menu.AddItem(new GUIContent("Option 1"), false, () =>
{
Debug.Log("Option 1 selected");
});
menu.AddItem(new GUIContent("Option 2"), false, () =>
{
Debug.Log("Option 2 selected");
});
menu.ShowAsContext();
Event.current.Use();
}
};
}
private void OnGUI()
{
serializedObject.Update();
list.DoLayoutList();
serializedObject.ApplyModifiedProperties();
}
}
```
在这个示例中,我们在ReorderableList的onMouseUpCallback函数中检测鼠标右键按下事件,并创建一个带有两个菜单项的GenericMenu对象。当菜单项被选中时,会调用相应的回调函数。在这个示例中,我们只是简单地记录了选中的菜单项,但你可以根据需要执行任何操作。
阅读全文