Is there an existing function available, or do I need to write one, to let me create a given folder structure in one go, making all subfolders as needed?
This is pretty normal for most OS file system APIs, but Unity seems to insist that it can’t make a given folder without its immediate parent already existing.
So if for example you want a folder Assets/Foo/Bar/Final you can’t just ask for that, as it will fail. You have to first create Foo, then create Bar, then create Final.
There’s really no reason to use the AssetDatabase API to create folders. The only upside I can see is that it gives you the folder’s GUID and immediately updates the database.
But there’s no problem using System.IO.Directory.CreateDirectory, which will automatically create folders recursively. You can e.g. immediately create an asset inside that folder and Unity won’t complain, so I don’t see why you’d have to use the AssetDatabase API.
That is what I thought and I had done that in the past, but when I went to do that with the most recent work I kept running into bugs where Unity did not see the newly created folders. The only way I could reliably get Unity to see the new folders for code that executed as part of the same bit of work was to create the folders using AssetDatabase.
Yep. It never seemed to “register” until later. In other words if I am doing some asset work and want to import some files, the code would create the target folders, then call AssetDatabase.CreateAsset() but that second call would error out saying the folder didn’t exist. Doing it with AssetDatabase.CreateFolder() does seem to register it though.
Weird. When you call AssetDatabase.Refresh() does Unity produce the metafiles for those folders? I imagine until you see metafiles appear for the folders, which I assume happened on a .Refresh() but apparently not, the DB won’t know about them…
It looks like this is not done synchronously, just runs the update in background. Probably if you register an async callback in the editor, it will work.
On Unity 2019.2, I can execute the following without problems, Dir/Subdir/Subsubdir and test.mesh get created without errors and appear immediately in the project view:
var assetPath = "Assets/Dir/Subdir/Subsubdir/test.mesh";
Directory.CreateDirectory(Path.GetDirectoryName(assetPath));
AssetDatabase.CreateAsset(new Mesh(), assetPath);