- Home /
How to load Audioclip using resources.load
I have the following code in one of my scripts that won't seem to work properly:
string tempNextEx = currentExercise[exNum + 1];
AudioClip clip = Resources.Load<AudioClip> (tempNextEx);
AudioSource.PlayClipAtPoint (clip, transform.position);
It doesn't seem to register the audioclip when I use the variable tempNextEx, even though I triple checked that the strings in currentExercise[] are identical to the names of each audioclip. However it does work if I manually type in the name of an audioclip rather than use the variable tempNextEx.
Since the order of the exercises is random, I can't manually code in the next exercise clips.
I also attempted the following code, which also didn't work:
foreach (AudioClip clip in exerciseClips) {
if (clip.name == tempNextEx) {
AudioSource.PlayClipAtPoint (clip, transform.position);
}
}
If anyone knows a solution to this issue, it would be greatly appreciated.
The code looks fine.
is the clip directly under the Resources folder or is it under any sub folder ?
Answer by orxyandcrake · Jun 03, 2019 at 05:32 AM
Have you tried adding tempNextEx.ToString()
? Sounds silly I know, but worth a try.
Also the argument is a filepath not a filename, with Resource folder as root, in case that helps.
I have come across an issue if you try to build a composite string it fails. So construct the filepath out of one string before committing it to an array.
It might be the array that you are holding the value in that's causing the issue. It's possible there is a metadata issue with how unity handles the Load<> function.
This is the approach I use, yes it could be better but it works for now.
public class ImageLocations
{
static readonly string runes = "Sprites/Icons/Runes/";
public static readonly string runeSlotIcon = runes + "RuneSlotIcon";
}
Note that Load<>() would only accept one level of abstraction. So the following broke Load<>() Don't do this:
public class ImageLocations
{
static readonly string sprites = "Sprites/";
static readonly string icons = sprites + "Icons/";
static readonly string runes = icons + "Runes/";
public static readonly string runeIcon = runes + "RuneIcon";
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Algorithm for loading sounds 1 Answer
2D Platformer (Unity 4.3) - How are the AudioClip arrays initialized? 1 Answer
Array not updating in inspector 0 Answers