其他分享
首页 > 其他分享> > 生成资源路径常量

生成资源路径常量

作者:互联网

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

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 并不会有此问题

标签:infoList,return,常量,路径,private,生成,static,using,string
来源: https://blog.csdn.net/BLACKLIKESWHITE/article/details/122562121