获取Unity节点路径
- 解决目的: 避免手动拼写节点路径的时候,出现路径错误导致获取不到节点的情况。
- 解决效果: 添加如下脚本之后,将自动复制路径到剪贴板中,在代码中通过 ctrl+v 粘贴路径
- 代码如下:
public class CustomMenuItems{[MenuItem("GameObject/自定义功能/获取GameObject路径", false, 0)]static void GetGameObjectPath(MenuCommand menuCommand){GameObject selectedObject = menuCommand.context as GameObject;if (selectedObject != null){string path = GetFullPath(selectedObject.transform);Debug.Log($"GameObject路径: {path}");// 复制到剪贴板EditorGUIUtility.systemCopyBuffer = path;}}// 获取 GameObject 的完整层级路径static string GetFullPath(Transform transform){string path = transform.name;while (transform.parent != null){transform = transform.parent;// 如果父节点名称是 "Panel",就停止遍历if (transform.name == "Panel"){path = transform.name + "/" + path;break;}path = transform.name + "/" + path;}return path;}}
效果如下图所示: