How to find all AudioClips in Resources folder and play them?
I have a problem: in my main menu I want to play random song from Resources folder, but it seems like I'm doing it wrong. Also I have public void "NextTrack()" to play next song. Can someone help me with this problem? Here is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class music_main_menu : MonoBehaviour
{
AudioSource audioSource;
// Start is called before the first frame update
void Start()
{
object[] audioList = Resources.FindObjectsOfTypeAll(typeof(AudioClip));
Debug.Log(audioList);
}
public void NextTrack()
{
audioSource.Stop();
audioSource.PlayDelayed(1f);
}
}
You say you're doing it wrong but don't say what's happening?
Are you seeing anything in the debug output?
You seem to be grabbing all the audio files and placing them into an array named audioList, but then don't actually do anything with it?
I'd probably change the next track method to do something like:
audiosource=GetComponent<AudioSource>();
audiosource.Stop();
audiosource.clip=audioList[Random.Range(0,audiosource.length-1)];
audiosource.Play(0);
I tried to Debug either my audioList array and it's length.... It's always at 2, no matter how much I put audio files in Resources folder.
I fixed next track method before posting, forgot to include. About issue: on Debug.Log it shows me
UnityEngine.AudioClip[]
But I don't really understand what I need to do next, because as far as I know I can't use this method without any audioclips, so can be there another way to find and put in my array audio files or I just need something else to put in my script?
Answer by KevRev · Apr 14, 2019 at 12:19 PM
No you can load the resources into an array, just do it sightly differently.
This link to unity docs shows how to load and reference a bunch of textures from the resources folder.
Adapt this code for audio clips and you should be fine. Unity Doc Resources.LoadAll
Your answer
![](https://koobas.hobune.stream/wayback/20220612195432im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to play audio while reloading a weapon ammo in unity 3d C# Scripting ? 0 Answers
Newbie with OnTriggerEnter & Audio Files 0 Answers
AudioClip not showing up in inspector CSHARP 1 Answer
Audio or Music continuing to play between scenes 1 Answer
after adding AudioSource component through script the audio is paused 0 Answers