Unity UI Dropdown options from folder
I have this dropdown and I want to read in all the files in certain folder and them put them as options for the dropdown.
if (obj.name.Contains("AudioSphere"))
{
// Finding the dropdown menu with tag "audioDropdown"
Dropdown dropdown = GameObject.FindGameObjectWithTag("audioDropdown");
// Finding all the music files
FileInfo[] options = getAudioFiles();
// add Options to the dropdown from list
for (FileInfo data : options) {
dropdown.AddOptions(new Dropdown.OptionData(data.Name));
}
}
It is full of errors and I need some help with them. New to all these UI things in Unity.
private FileInfo[] getAudioFiles()
{
String path = Application.dataPath + "/Resources/Audiofiles";
// How to check if exists?
DirectoryInfo audioFolder = new DirectoryInfo(@path);
FileInfo[] audioFiles = audioFolder.GetFiles();
throw new NotImplementedException();
}
This is how I am trying to solve this task. If there is a better way feel free to share them with me.
Answer by Showoffz · Apr 23, 2016 at 01:14 PM
audioFiles = getAudioFiles();
char[] delimiterChars = { '/', '\\' };
pickAudio.options.Clear();
foreach (string c in audioFiles)
{
pickAudio.options.Add(new Dropdown.OptionData() { text = System.IO.Path.GetFileName(c) });
}
private string[] getAudioFiles()
{
string path = Application.dataPath + "/Resources/Audiofiles";
string[] filePaths = Directory.GetFiles(@path, "*.ogg");
foreach (string file in filePaths)
{
// Debug.Log(file);
}
return filePaths;
}
And later I find the files like so:
WWW m_get = new WWW("file://" + audioFiles[pickAudio.value]);
AudioSource.PlayOneShot(m_get.audioClip);
you should not do this ... does it work if you bulid your project?
Answer by Soraphis · Apr 23, 2016 at 03:12 PM
this works for me:
public string[] FileNamesFromFolder<T>(string folderpath) where T : UnityEngine.Object{
var allfiles = Resources.LoadAll<T>(folderpath);
return allfiles.Select(obj => obj.name).ToArray();
}
say, you want all AudioClip-object-names from the folder "Resources/Audiofiles"
you'd call the function:
var audioclipNames = FileNamesFromFolder<AudioClip>("Audiofiles");
it also works in custom editor windows (just tested it like here: http://pastebin.com/25rdMK2h)
Thank you for your reply ! $$anonymous$$anaged to clean up my code thanks to your hints.
Your answer
Follow this Question
Related Questions
How to save and load complete gameobjects 0 Answers
Resources.Load() .fbx file with multiple mesh children. 1 Answer
WebGl taking too long to load. size is large 1 Answer
Unity won't load!!!! 2 Answers
Auto save and auto load on quit app. 1 Answer