Quicki Quicki - 1 year ago 70
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>();

To the second line:

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

enter image description here

Answer Source

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>();

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");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download