生成资源路径常量

游戏开发时,加载预制体,图片,场景等资源时,有时会写入很多字符串在代码里。
为了方便,可以把资源路径生成静态常量,方便调用

1.选择生成资源路径的文件夹
2.选择需要的文件类型
3.拼接字符串
4.生成常量代码

#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;

public class PathCreate
{
    /// <summary>
    /// 路径常量代码生成位置
    /// </summary>
    private static string constValuePath = Application.dataPath + "/Scripts/Const";
    private static string formatStr = "    public static string {0} = \"{1}\";\n";

    [MenuItem("Assets/生成预制体路径", priority = 0)]
    static void GetPath() {

        string selectPath = GetSelectPath();
        if (selectPath == null) return;
        
        List<FileSystemInfo>       assets      = GetPathAsset(selectPath);
        Dictionary<string, string> usefulAsset = GetUsefulAsset(assets);

        string directoryName = selectPath.Split('/').Last();
        string scriptName    = $"Path{directoryName}";

        StringBuilder sb = new StringBuilder();
        sb.Append($"public class {scriptName}\n");
        sb.Append("{\n");

        foreach (KeyValuePair<string, string> keyValuePair in usefulAsset)
        {
            sb.Append(string.Format(formatStr, keyValuePair.Key, keyValuePair.Value));
        }
        sb.Append("\n}");

        string filePath = constValuePath + "/" + scriptName + ".cs";
        FileTool.DeleteFile(filePath);
        FileTool.WriteFile(filePath,sb.ToString());
        AssetDatabase.Refresh();
    }

    /// <summary>
    /// 获取当前选中的路径
    /// </summary>
    /// <returns></returns>
    private static string GetSelectPath() {
        if (Selection.objects == null)
        {
            Debug.LogError("当前未选中任何物体");
            return null;
        }
        Object select = Selection.objects[0];
        return AssetDatabase.GetAssetPath(select);
    }

    /// <summary>
    /// 获取当前文件夹下的所有文件
    /// </summary>
    /// <param name="assetPath"></param>
    /// <returns></returns>
    private static List<FileSystemInfo> GetPathAsset(string assetPath) {
        List<FileSystemInfo> systemInfoList = new List<FileSystemInfo>();
        PathOperation(assetPath, (fileSystemInfo) =>
        {
            systemInfoList.Add(fileSystemInfo);
        });
        return systemInfoList;
    }

    /// <summary>
    /// 需要生成路径的文件类型
    /// </summary>
    private static List<string> usefulExtension = new List<string>()
    {
        ".prefab",".unity",".mp3",".wav",".ogg"
    };
    /// <summary>
    /// 剔除不需要的文件类型
    /// </summary>
    /// <param name="infoList"></param>
    /// <returns></returns>
    private static Dictionary<string,string> GetUsefulAsset(List<FileSystemInfo> infoList) {
        Dictionary<string,string> pathDict = new Dictionary<string, string>();
        for (int i = 0; i < infoList.Count; i++)
        {
            for (int j = 0; j < usefulExtension.Count; j++)
            {
                if (infoList[i].Extension == usefulExtension[j])
                {
                    pathDict.Add(GetVariableName(infoList[i].Name,infoList[i].Extension),
                                 GetVariableValue(infoList[i].FullName,infoList[i].Extension));
                }
            }
        }

        return pathDict;
    }

    /// <summary>
    /// 生成的常量量名称
    /// </summary>
    /// <param name="str"></param>
    /// <param name="extensionStr"></param>
    /// <returns></returns>
    private static string GetVariableName(string str,string extensionStr) {

        str = str.Replace(extensionStr, "");
        return str;
    }
    /// <summary>
    /// 需要替换掉的路径前缀
    /// </summary>
    private static string currentPath = Application.dataPath + "/Resources/";
    private static string GetVariableValue(string str,string extensionStr) {
        
        string resourcePath = str.Replace("\\", "/");
        resourcePath = resourcePath.Replace(currentPath, "");
        resourcePath = resourcePath.Replace(extensionStr, "");
        return resourcePath;
    }

    /// <summary>
    /// 递归查找所有的文件
    /// </summary>
    /// <param name="assetsPath"></param>
    /// <param name="ac"></param>
    private static void PathOperation(string assetsPath, Action<FileSystemInfo> ac)
    {
        DirectoryInfo dir = new DirectoryInfo(assetsPath);

        FileSystemInfo[] files = dir.GetFileSystemInfos();
        foreach (var fileSystemInfo in files)
        {
            if (fileSystemInfo is DirectoryInfo)
            {
                PathOperation(fileSystemInfo.FullName, ac);
            }
            ac?.Invoke(fileSystemInfo);
        }
    }
}
#endif

代码都已加入注释,需要的可以根据项目具体需要进行更改
注意事项:
当Unity的Project窗口采用Two Clumn Layout时,
点击左侧文件夹不会被视为选中文件夹,
需要鼠标点击右侧空白位置。文件夹选中示意图
如图,只有点击右侧任意空白位置才会被Unity识别为选中了Excel文件夹
采用 One Clumn Layout 并不会有此问题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值