Saturday, March 16, 2019

c# - How to use Resources.Load with an AudioClip in Unity?


I'm trying to load an audio clip that's in my assets directory and play it. Here is my C# script:


if (Input.GetKeyDown(KeyCode.X))
{
audioSource = gameObject.GetComponent();
Debug.Log((audioSource == null) ? "Audio source is null" : "Audio Source is not null");
string path = "Sounds/Aurora/Aurora_IGSSin";
Debug.Log(path);
sound = (AudioClip)Resources.Load(path, typeof(AudioClip)) ;
Debug.Log((sound == null) ? "Sound is null" : "Sound is not null");

}

//Output:
//Audio source is not null
//Sounds/Aurora/Aurora_IGSSin
//Sound is null

There is an AudioSource component attached to this object, as proved by the first Debug.Log(). Attached is a picture of my folder, proving that the file path is correct. I've seen 90 different posts and tried this 81 different ways, including using the file extension in the path, omitting the directory and only including the file name, omitting (AudioClip) before Resources.Load(), using as AudioClip rather than typeof(AudioClip) and none of it has worked.


Please, someone help me before I pull my hair out over this. I'm incredibly flustered over being stuck on something that should be so simple, and I'd like to get on with my project.


My Project Directory:



My Project Directory



Answer



Resources.Load()

requires that you have a Resources directory as a chils of the Assets directory where you put everything that has to be loaded with that method.


In your case create a Resources directory and then move in your Sounds directory.


EDIT: the you can simplify your call in this way


sound = Resources.Load(path);

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...