Loop through folder of assets and put names in array

Hi guys,

I am trying to loop through a folder of assets and get the names of each asset.

With the names I want to create a button for each that will eventually be used to create an instance of that asset(prefab).

I am getting this error: error CS0030: Cannot convert type System.IO.FileInfo' to string’

void vehicleNames()
{
		DirectoryInfo dir = new DirectoryInfo("Assets/Resources/Vehicles");
		FileInfo[] info = dir.GetFiles("*.prefab");
		info.Select(f => f.FullName).ToArray();
		foreach (FileInfo f in info) 
		{ 
			GUI.Label(new Rect(300,500,50,20), (string)f);
		}
}

Any help would be much appreciated :slight_smile:

I know I’m late to the party but I wanted to put this in here anyways because it’s Linq and I like Linq.

info.Select(f => f.FullName).ToArray();

Doing that by itself does nothing because the ToArray() returns the array result for use with a setter, it doesn’t modify the original object of info. You can tell because in your foreach loop, your iterator variable is a FileInfo type, which is a complex object and can’t be turned into a string.

You could either do this:

void vehicleNames()
{
       DirectoryInfo dir = new DirectoryInfo("Assets/Resources/Vehicles");
       FileInfo[] info = dir.GetFiles("*.prefab");
       var fullNames = info.Select(f => f.FullName).ToArray();
       foreach (string f in fullNames) 
       { 
         GUI.Label(new Rect(300,500,50,20), f);
       }
}

Or you could do this:

void vehicleNames()
{
       DirectoryInfo dir = new DirectoryInfo("Assets/Resources/Vehicles");
       FileInfo[] info = dir.GetFiles("*.prefab");
       foreach (FileInfo f in info) 
       { 
         GUI.Label(new Rect(300,500,50,20), f.FullName);
       }
}

(string)f // won’t work

You could try:

f.ToString()

(checking MSDN for more info)

but f.Name might suit you better.

Load All Prefabs In Directory · GitHub i made a thing that might help in this gist