Unity在Project右键点击物体之后获取到点击物体的名称
描述:
在Unity的Project右键点击物体之后选择对应的菜单选项点击之后打印出物体的名称
注意事项
如果获取到文件或者预制体需要传递objcet
类型,然后使用 GameObject.Instantiate((GameObject)selectproject);
在场景中创建,销毁时候使用DestroyImmediate(selectproject);
销毁。
代码
代码需要放到Editor
文件夹下
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;public class RightMouseButtonExpansion : EditorWindow
{private static Dictionary<int, string> _itemsCache = new Dictionary<int, string>();private static int GetInstanceIDFromPath(string path){if (_itemsCache.ContainsKey(path.GetHashCode())){return int.Parse(_itemsCache[path.GetHashCode()]);}else{Object obj = AssetDatabase.LoadMainAssetAtPath(path);int instanceID = obj.GetInstanceID();_itemsCache.Add(path.GetHashCode(), instanceID.ToString());return instanceID;}}[MenuItem("Assets/wyhEditorExtension/Get Selected Object Name")]static void GetSelectedObjectName(){Object selectedObject = Selection.activeObject;string path = AssetDatabase.GetAssetPath(selectedObject);int instanceID = GetInstanceIDFromPath(path);Object obj = EditorUtility.InstanceIDToObject(instanceID);Debug.Log("右键选中的物体的名称是:" + obj.name);}public static void OnProjectItemContextMenu(int instanceID, Rect selectionRect){string path = AssetDatabase.GetAssetPath(InstanceIDToObject(instanceID));string name = AssetDatabase.LoadMainAssetAtPath(path).name;//打印出物体的名称Debug.Log(name);}static Object InstanceIDToObject(int instanceID){return EditorUtility.InstanceIDToObject(instanceID);}
}