Checking if a folder exists?

I’m doing the walker boy tutorials. Lab 3 is about making unity tools to improve workflow. Only just started, and the first part is about creating a menu option that will automatically generate folders for your project. I got that working using the .NET code in their video.

However, while Eric (or Chad, I’m not sure who does the videos), was looking through the Unity script reference for a function to create a folder, there was no CreateFolder, because it wasn’t added until 3.4 - since I am endeavouring to actually learn how to program and different ways of doing it, I have a menu option to create the folders for both methods.

The .NET method they give is something like this (sorry, it might not be correct syntax, I am at work atm and my computer I do the tutorials on is at home)

Directory.Adddirectory(Application.dataPath + “/FolderName”); (I don’t think the “adddirectory” bit is correct, but you get the idea)

I got the unity function working like this - "AssetDatabase.CreateFolder(“Assets”, “FolderName”);

And that works. The difference between the .NET and the unity function is that the .NET function will not create a folder if it already exists, whereas, if you do it with the unity CreateFolder method, it will create a series of folders “FolderName, FolderName 01” etc.

So, since I want to learn, instead of just following the tutorial, how would I be able to check if a folder already exists, and then create it if it doesn’t, using the unity CreateFolder function?

I’m also looking for an answer to this question. I love that there’s an AssetDatabase method for creating a folder, but it seems very odd that there isn’t a straightforward way to check if that folder already exists.

Actually, what I think I would prefer is if the method arguments were more like this:

static function CreateFolder (parentFolder : String, newFolderName : String, proliferateIfExists : boolean = true) : String

I ended up doing something like this to check if a Materials folder existed next to my model asset:

if (!System.IO.Directory.Exists(Application.dataPath + System.IO.Path.GetDirectoryName(assetPath).TrimStart("Assets".ToCharArray()) + "/Materials")) {
	AssetDatabase.CreateFolder(System.IO.Path.GetDirectoryName(assetPath), "Materials");
}
2 Likes