Quicki Quicki - 19 days ago 6
C# Question

Adding audioClip from the Resources folder through code

How can I add and play short audioClip by name in code in Unity?
I tested a lot of samples from the Internet but anyone doesn't work.

AudioSource audio = gameObject.AddComponent<AudioSource>();
audio.Play((AudioClip)Resources.Load("clip1"));‚Äč


To the second line:


Assets/Resources/ClickAction.cs(14,55): error CS1525: Unexpected symbol `'


enter image description here

Answer

AudioSource.Play() does not take AudioClip as a parameter.

AudioSource.PlayOneShot() does. Pawel also talked about this except that no code example was provided in his answer.

This is what the play prototype looks like:

public void Play();
public void Play(ulong delay);

None of them takes AudioClip as parameter.

So it should be:

AudioSource audio = gameObject.AddComponent<AudioSource>();
audio.PlayOneShot((AudioClip)Resources.Load("clip1"));

You can still use the the Play() function from your question but you must first assign AudioSource.clip with (AudioClip)Resources.Load("clip1"); before calling the Play() function.

So, this should work too:

AudioSource audio = gameObject.AddComponent<AudioSource>();
audio.clip = (AudioClip)Resources.Load("clip1");
audio.Play();
Comments