ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

生成资源路径常量

2022-01-18 16:30:00  阅读:121  来源: 互联网

标签:infoList return 常量 路径 private 生成 static using string


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

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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有