正常咱們官網(wǎng)查到的Unity API
public static string CreateFolder (string parentFolder, string newFolderName);
但是這樣的話就只能創(chuàng)建固定的命名了臭杰。
所以我查了一下官網(wǎng)的Create Folder是怎么實(shí)現(xiàn)的
// Create a folder
[ShortcutManagement.ShortcutAttribute("Project Browser/Create/Folder", typeof(ProjectBrowser), KeyCode.N, ShortcutManagement.ShortcutModifiers.Shift | ShortcutManagement.ShortcutModifiers.Action)]
public static void CreateFolder()
{
StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<DoCreateFolder>(), "New Folder", EditorGUIUtility.IconContent(EditorResources.emptyFolderIconName).image as Texture2D, null);
}
附上地址:UnityCsReference/ProjectWindowUtil.cs at master · Unity-Technologies/UnityCsReference (github.com)
她是用了一個(gè)StartNameEditingIfProjectWindowExists
的方法
我查了一下這個(gè)方法
public static void StartNameEditingIfProjectWindowExists(int instanceID, EndNameEditAction endAction, string pathName, Texture2D icon, string resourceFile)
附上地址:Class ProjectWindowUtil (stephenhodgson.github.io)
他EndNameEditAction
有一個(gè)Action,官網(wǎng)是這么寫(xiě)的
internal class DoCreateFolder : EndNameEditAction
{
public override void Action(int instanceId, string pathName, string resourceFile)
{
string guid = AssetDatabase.CreateFolder(Path.GetDirectoryName(pathName), Path.GetFileName(pathName));
Object o = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid), typeof(Object));
ProjectWindowUtil.ShowCreatedAsset(o);
}
}
因?yàn)槲抑恍枰谧钔鈱用锩Γ锩娴慕Y(jié)構(gòu)都是寫(xiě)死的车胡,所以我重寫(xiě)了這個(gè)方法來(lái)實(shí)現(xiàn)我需要再里面嵌套其它文件夾惠奸。
using System.IO;
using UnityEditor;
using UnityEditor.Experimental;
using UnityEditor.ProjectWindowCallback;
using UnityEngine;
public class CreateArtResFolder : Editor
{
[MenuItem("Assets/Create/Folder.ArtRes", priority = 15)]
static void Init()
{
CreateArtFolder();
Debug.Log("已創(chuàng)建文件夾");
}
static void CreateArtFolder()
{
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, CreateInstance<DoCreateFolder>(), "New Folder", EditorGUIUtility.IconContent(EditorResources.folderIconName).image as Texture2D, null);
}
}
internal class DoCreateFolder : EndNameEditAction
{
public override void Action(int instanceId, string pathName, string resourceFile)
{
string guid = AssetDatabase.CreateFolder(Path.GetDirectoryName(pathName), Path.GetFileName(pathName));
AssetDatabase.CreateFolder(pathName, "Materials");
Object o = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid), typeof(Object));
ProjectWindowUtil.ShowCreatedAsset(o);
}
}
在底下DoCreateFolder
類(lèi)里面寫(xiě)內(nèi)層的文件夾結(jié)構(gòu)
增加一個(gè)AssetDatabase.CreateFolder(pathName, "Materials");
pathName
可以直接拿到的當(dāng)前創(chuàng)建好后的文件夾完整內(nèi)部路徑,所以可以按照這個(gè)思路往里面添加其它文件夾。
附上 Unity 官方源碼地址:Unity-Technologies/UnityCsReference: Unity C# reference source code. (github.com)