You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity编辑器脚本:如何获取右键点击的Assets文件夹路径?

Unity编辑器脚本:右键文件夹生成ReadMe(无Selection遍历版)

修改思路

不用遍历Selection.objects,直接借助Unity编辑器菜单的MenuCommand参数获取右键点击的目标文件夹对象,精准拿到路径的同时避免遍历操作。

完整修改后的脚本

using UnityEditor;
using UnityEngine;
using System.IO;

public static class CustomMenuItems
{
    // 添加MenuCommand参数,接收右键点击的上下文对象
    [MenuItem("Assets/Create/Custom ReadMe File", false, 81)]
    private static void CreateReadMeFile(MenuCommand menuCommand)
    {
        string path = "Assets";
        
        // 从MenuCommand获取右键点击的目标对象
        Object targetObj = menuCommand.context;
        if (targetObj != null)
        {
            string objPath = AssetDatabase.GetAssetPath(targetObj);
            // 验证是否为有效文件夹路径
            if (!string.IsNullOrEmpty(objPath) && Directory.Exists(objPath))
            {
                path = objPath;
            }
        }

        // 拼接ReadMe文件的完整路径
        string filePath = Path.Combine(path, "ReadMe.txt");

        if (!File.Exists(filePath))
        {
            File.WriteAllText(filePath, "这是自定义的ReadMe文件。\n\n你可以在这里添加项目说明、操作指引等内容。");
            AssetDatabase.Refresh(); // 刷新资源库,让新文件立刻显示在面板中
        }
        else
        {
            Debug.LogWarning("选中的文件夹中已存在ReadMe.txt文件,无需重复创建。");
        }
    }
}

关键改动说明

  • 给CreateReadMeFile方法添加MenuCommand参数:Unity会自动将右键点击的对象传入menuCommand.context,无需手动遍历选中对象列表。
  • 直接通过menuCommand.context获取目标对象,验证其路径是否为文件夹,替换原有的遍历逻辑。
  • 若右键点击Assets面板空白区域(未选中具体文件夹),则默认使用Assets根目录,保留原有降级逻辑。

内容的提问来源于stack exchange,提问作者Daniel Lip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 07:20:02